python send http request and get response

Python Send HTTP Request and Get Response

If you're working with APIs and web services, you will need to send HTTP requests and receive responses. In Python, you can use the built-in requests module to do that.

Sending GET Requests

If you want to send a GET request to a web server, you can use the requests.get() function. Here's an example:


import requests

response = requests.get('https://www.example.com')
print(response.content)

In this example, we sent a GET request to https://www.example.com and received the response. We then printed the content of the response using the content attribute.

Sending POST Requests

If you want to send a POST request to a web server, you can use the requests.post() function. Here's an example:


import requests

data = {'username': 'testuser', 'password': 'testpass'}
response = requests.post('https://www.example.com/login', data=data)
print(response.status_code)

In this example, we sent a POST request to https://www.example.com/login with a dictionary of data containing the username and password. We then printed the status code of the response using the status_code attribute.

Sending Headers

Sometimes you may need to send headers along with your requests. You can do this by passing a dictionary of headers to the headers parameter of the request function. Here's an example:


import requests

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
response = requests.get('https://www.example.com', headers=headers)
print(response.content)

In this example, we sent a GET request to https://www.example.com with a custom User-Agent header. We then printed the content of the response using the content attribute.

Conclusion

Sending HTTP requests and receiving responses in Python is easy with the requests module. You can send GET and POST requests, send headers, and receive responses with just a few lines of code.