Jeeva
Jeeva

Reputation: 4835

HTTP/1.1 vs HTTP/1.0 Python socket

I am trying to send and receive HTTP data using the Python socket. But when I use HTTP/1.0 it works but when I use HTTP/1.1 it just keeps waiting...

This code works

import socket

client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('httpbin.org', 80)
client_socket.connect(server_address)

request_header = 'GET /ip HTTP/1.0\r\nHost: httpbin.org\r\n\r\n'
client_socket.send(request_header.encode())

response = ''
while True:
    recv = client_socket.recv(1024)
    if not recv:
        break
    response += recv 

print(response)
client_socket.close()

This doesn't work

import socket

client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('httpbin.org', 80)
client_socket.connect(server_address)

request_header = 'GET /ip HTTP/1.1\r\nHost: httpbin.org\r\n\r\n'
client_socket.send(request_header.encode())

response = ''
while True:
    recv = client_socket.recv(1024)
    if not recv:
        break
    response += recv 

print(response)
client_socket.close() 

If the HTTP/1.1 is the problem then how could I detect if it doesn't support HTTP/1.1?

Upvotes: 2

Views: 1337

Answers (1)

Barmar
Barmar

Reputation: 781726

HTTP/1.1 defaults to persistent connections. If you want the server to close the connection after it sends the response, you need to send the Connection: close header.

request_header = 'GET /ip HTTP/1.1\r\nHost: httpbin.org\r\nConnection: close\r\n\r\n'

Upvotes: 2

Related Questions