1. import http.client
  2. import json
  3. def create_request_headers(method, url, data=None):
  4. """
  5. Initializes request headers for a temporary solution with synchronous execution.
  6. Args:
  7. method (str): HTTP method (e.g., "POST", "GET").
  8. url (str): The URL to make the request to.
  9. data (str, optional): The request data (JSON string). Defaults to None.
  10. Returns:
  11. dict: A dictionary containing the request headers.
  12. """
  13. headers = {
  14. 'Content-Type': 'application/json', # Indicate JSON data
  15. 'Accept': 'application/json' # Request JSON response
  16. }
  17. if data:
  18. headers['Content-Length'] = len(data.encode('utf-8')) #Content length is important for POST/PUT
  19. return headers
  20. def make_request(method, url, headers, data=None):
  21. """
  22. Makes an HTTP request with the specified headers.
  23. Args:
  24. method (str): HTTP method (e.g., "POST", "GET").
  25. url (str): The URL to make the request to.
  26. headers (dict): The request headers.
  27. data (str, optional): The request data (JSON string). Defaults to None.
  28. Returns:
  29. str: The response body as a string.
  30. """
  31. conn = http.client.HTTPSConnection(url)
  32. try:
  33. if method == "GET":
  34. conn.request(method, url, headers=headers)
  35. else:
  36. conn.request(method, url, body=data, headers=headers)
  37. response = conn.getresponse()
  38. return response.read().decode('utf-8')
  39. finally:
  40. conn.close()
  41. if __name__ == '__main__':
  42. #Example usage
  43. url = "https://httpbin.org/post"
  44. data = '{"key1": "value1", "key2": "value2"}'
  45. headers = create_request_headers("POST", url, data)
  46. response = make_request("POST", url, headers, data)
  47. print(response)

Add your comment