0

Earlier I a question asking how to create a connection before calling POST, GET etc using the Python Requests library:

Create connection using Python Request library before calling post/get etc

turns out I couldn't.

I'm now using the httpclient library and have this:

import http.client as httplib

params = my_params()
headers = {"Connection": "Keep-Alive"}

conn = httplib.HTTPSConnection("api.domain.com:443")

conn.request("POST", "/api/service", params, headers)
response = conn.getresponse()

I was hoping it would establish the connection first. However, the line:

conn = httplib.HTTPSConnection("api.domain.com:443")

is only taking 2ms to complete and I know the latency to the recipient is approximately 95ms. So, I presume this line isn't creating the connection and it's still being created along with the POST.

How can I make a POST request in Python, where the connection is already established before make the POST request?

Something like:

conn = https.connect("api.domain.com:443")
# Connection established before making POST
conn.request("POST", "/api/service", params, headers)
intrigued_66
  • 16,082
  • 51
  • 118
  • 189

1 Answers1

2

Yes, in http.client library, the connection is established when you make the request using the request() method. The line conn = httplib.HTTPSConnection("api.domain.com:443") creates the connection object but doesn't establish the actual connection.

If you want to establish the connection before making the request, you can use the connect() method.

Like this:

import http.client as httplib

params = my_params()
headers = {"Connection": "Keep-Alive"}

conn = httplib.HTTPSConnection("api.domain.com:443")
conn.connect()

conn.request("POST", "/api/service", params, headers)
response = conn.getresponse()

conn.close()

Source: https://docs.python.org/3/library/http.client.html#http.client.HTTPConnection.connect