Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python make a POST request after the connection is already established

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading