So as my title said, Im making a small http library with basic get and post requests. I have the get request done, but my post request is acting weird. Anytime I pass data to the post, it doesn't get a response. It seems to work just fine when I don't pass the body attribute (last one). Im not trying to use the requests library, i'm trying to make one myself.
Can anyone see what I'm doing wrong? I feel like I am missing a header but I don't know which.
import socket
from urllib.parse import urlparse
import json
TCRLF = "\r\n\r\n"
CRLF = "\r\n"
def post(url, headers=None, data=""):
connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
request = build_request("POST", url, headers, data)
print("request: " + request)
print("url:" + url)
print("headers :" + str(headers))
url = urlparse(url)
connection.connect((url.hostname, url.port or 80))
connection.sendall(request.encode("UTF-8"))
response = connection.recv(4096).decode("UTF-8")
print("response: " + response)
#
# (response_header, response_body) = response.split(TCRLF)
# response_body = json.loads(response_body)
#
# print(response_header)
# print(response_body)
return None
def build_request(req_type, url, headers=None, body=""):
url = urlparse(url)
hostname = url.hostname
path = url.path or "/"
query = url.query
port = url.port or 80
print("hostname" + hostname)
print("path : " + path)
print("query :" + query)
print("port :" + str(port))
print("body:" + str(body))
uri = "{}?{}".format(path, query) if query else path
formatted_headers = "".join(
"{}:{}\r\n".format(k, v) for k, v in headers.items())
print("formatted: "+ formatted_headers)
requestGet = "GET " + uri + " HTTP/1.0" + CRLF + "Host:" + hostname + CRLF + formatted_headers + TCRLF
##TODO body failing when passing object
requestPost = "POST " + uri + " HTTP/1.0" + CRLF + "Host: " + hostname + CRLF + "Content-Length: " + str(
len(body)) + CRLF + formatted_headers + TCRLF + body + TCRLF
print("Request" + requestPost)
if req_type=="POST":
return requestPost
else:
return requestGet
def main():
post("http://httpbin.org/post", {"Content-Type": "application/json" }, "{'Assignment': 1}")
if __name__ == '__main__':
main()