Andrew
Andrew

Reputation: 11

Sending HTTP request line to jupyter with python

I tried to send a HTTP request to my jupyter notebook with the help of the module socket like this:

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect(('127.0.0.1', 8888))
    s.sendall(b'GET /api/contents HTTP/1.1 \n\n') # Maybe i didn't understand how HTTP requests work
    print(s.recv(1024))

Output(in the terminal where jupyter notebook was running):

Malformed HTTP message from 127.0.0.1: Malformed HTTP request line

And the data received is HTTP/1.1 400 Bad Request\r\n\r\n

And it says that it uses this delimiter re.compile(b'\r?\n\r?\n')

Jupyter Notebook Server API

Upvotes: 0

Views: 1557

Answers (1)

grapes
grapes

Reputation: 8636

If you dont want to supply any headers in your HTTP request, just terminate it with \r\n\r\n sequence:

s.sendall(b'GET /api/contents HTTP/1.1\r\n\r\n')

HTTP uses \r\n sequence as a line-delimiter (like in Windows) and double sequence (\r\n\r\n) to mark the request headers end. So normally the request would look like

GET /api/contents HTTP/1.1\r\n
User-Agent: blablah\r\n
....\r\n
\r\n
<HERE GOES REQUEST BODY>

Upvotes: 1

Related Questions