Skip to content

Instantly share code, notes, and snippets.

@tovask
Last active October 29, 2021 18:46
Show Gist options
  • Save tovask/8c88e2bd39ee5992a2d04573b5e55775 to your computer and use it in GitHub Desktop.
Save tovask/8c88e2bd39ee5992a2d04573b5e55775 to your computer and use it in GitHub Desktop.
http(s) request with body in python using socket
#!/bin/env python
"""
A simple example of using Python sockets for a HTTP(S) request
"""
import socket, ssl
host = "httpbin.org"
port = 443
method = "POST"
path = "/post"
body = "a=1"
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((host, port))
if port == 443:
s = ssl.wrap_socket(s)
request = "{method} {path} HTTP/1.1\r\n".format(method=method, path=path)
request += "Host: {host}\r\n".format(host=host)
request += "Accept: */*\r\n"
request += "User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0\r\n"
if len(body) > 0:
request += "Content-Type: application/x-www-form-urlencoded\r\n"
request += "Content-Length: {len}\r\n".format(len=len(body))
request += "\r\n"
request += body
print(request)
s.sendall(request.encode())
print(str(s.recv(4096), 'utf-8'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment