Fir let me clear I don't want to to use higher level APIs, I only want to use socket programming
I have wrote following program to connect to server using POST request.
import socket
import binascii
host = "localhost"
port = 9000
message = "POST /auth HTTP/1.1\r\n"
parameters = "userName=Ganesh&password=pass\r\n"
contentLength = "Content-Length: " + str(len(parameters))
contentType = "Content-Type: application/x-www-form-urlencoded\r\n"
finalMessage = message + contentLength + contentType + "\r\n"
finalMessage = finalMessage + parameters
finalMessage = binascii.a2b_qp(finalMessage)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.sendall(finalMessage)
print(s.recv(1024))
I checked online how POST request is created.
Somehow Paramters are not getting passed to the server. Do I have to add or remove "\r\n" in between the request?
Thanks in advance,
Regards,
Ganesh.
Best Solution
This line
finalMessage = binascii.a2b_qp(finalMessage)
is certainly wrong, so you should remove the line completely, another problem is that there is no new-line missing afterContent-Length
. In this case the request sent to the socket is (I am showing theCR
andLF
characters here as\r\n
, but also splitting lines for clarity):So obviously this does not make much sense to the web server.
But even after adding a newline and removing
a2b_qp
, there is still the problem is that you are not talkingHTTP/1.1
there; the request must have aHost
header for HTTP/1.1 (RFC 2616 14.23):Also you do not support chunked requests and persistent connections, keepalives or anything, so you must do
Connection: close
(RFC 2616 14.10):Thus, any
HTTP/1.1
server that would still respond normally to your messages withoutHost:
header is also broken.This the data that you should send to the socket with that request:
Note that you'd not add the
\r\n
in the body anymore (thus the length of body 29). Also you should read the response to find out whatever the error is that you're getting.On Python 3 the working code would say: