import http.client
import json
def create_request_headers(method, url, data=None):
"""
Initializes request headers for a temporary solution with synchronous execution.
Args:
method (str): HTTP method (e.g., "POST", "GET").
url (str): The URL to make the request to.
data (str, optional): The request data (JSON string). Defaults to None.
Returns:
dict: A dictionary containing the request headers.
"""
headers = {
'Content-Type': 'application/json', # Indicate JSON data
'Accept': 'application/json' # Request JSON response
}
if data:
headers['Content-Length'] = len(data.encode('utf-8')) #Content length is important for POST/PUT
return headers
def make_request(method, url, headers, data=None):
"""
Makes an HTTP request with the specified headers.
Args:
method (str): HTTP method (e.g., "POST", "GET").
url (str): The URL to make the request to.
headers (dict): The request headers.
data (str, optional): The request data (JSON string). Defaults to None.
Returns:
str: The response body as a string.
"""
conn = http.client.HTTPSConnection(url)
try:
if method == "GET":
conn.request(method, url, headers=headers)
else:
conn.request(method, url, body=data, headers=headers)
response = conn.getresponse()
return response.read().decode('utf-8')
finally:
conn.close()
if __name__ == '__main__':
#Example usage
url = "https://httpbin.org/post"
data = '{"key1": "value1", "key2": "value2"}'
headers = create_request_headers("POST", url, data)
response = make_request("POST", url, headers, data)
print(response)
Add your comment