2

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?

1
  • 1
    Why are you doing this with sockets instead of using a library like urllib2? HTTP is not a simple protocol, there are lots of details you need to understand. Commented Jun 8, 2019 at 5:38

1 Answer 1

2

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'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.