Reputation: 43
HI i'm very new to web development, don't really know a lot about the available python libraries. Sorry for being over descriptive.
My recent project is to make a script that will do a GET request on a website, fill up a form using POST and submit which will get the exam result of a student using the credentials provided. I used Wireshark to capture the original get and post request to receive the result.
my code generates the following post request
I tried to replicate the HTTP requests using the following which doesn't seem to work, the GET request does work and i can see the homepage on wireshark as tcp segment payloads but the POST request recieves a 200 OK code where it usually says "window.location.href="index.php?err=101"; ". I get the same result if i do a post request using curl. Besides when i print the response after POST request, pyCharm doesnt really print the result in a readable way, i did a bit of a research and it seems there's no default method that can print the response like curl does, i checked the tcp packets from my host which showed the mentioned err=101, any help to check where i'm slipping will be much appreciated. TIA
import socket
HOST = 'my website'
PORT = 80
temp = socket.gethostbyname(HOST)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
request = "GET / HTTP/1.1\r\nHost:%s\r\n\r\n" %HOST
s.send(request.encode())
response = s.recv(4096)
print(response)
headers = """\
POST /result.php HTTP/1.1\r
Content-Type: {content_type}\r
Content-Length: {content_length}\r
Host: {host}\r
Connection: keep-alive\r
\r\n"""
value_s = input("Whats the value to pass?")
parameters = "parametres" %str(value_s)
body_bytes = parameters.encode('ascii')
header_bytes = headers.format(
content_type="application/x-www-form-urlencoded",
content_length=len(body_bytes),
host=HOST + ":" + str(PORT)
).encode('iso-8859-1')
payload = header_bytes + body_bytes
response1 = str(s.recv(4096))
print(response1)
Upvotes: 0
Views: 276
Reputation: 169338
You shouldn't use the same socket for two subsequent requests unless you declare you will be doing keepalive, and you're not.
If you're not especially looking to learn all about the intricacies of HTTP, please just use the Requests library instead for making requests, like e.g. so:
import requests
value_s = input("Whats the value to pass?")
parameters = "parametres" % value_s
body = parameters.encode("iso-8859-1")
sess = requests.Session()
resp = sess.get("http://my-website/")
resp.raise_for_status()
print(resp.content)
resp = sess.post(
"http://my-website/result.php",
headers={"Content-Type": "application/x-www-form-urlencoded",},
body=body,
)
resp.raise_for_status()
print(resp.content)
Upvotes: 0