Reputation: 69
I just finished python course on a Codeacademy and read a book about networks. Now I want to send a GET message using HTTP protocol to a google server(or somewhere else) and read a request using python script only. But I don't want to use anything but socket module
The reason is that it seems to be very easy. Just create a TCP connections and send a message, then receive the answer. I feel being a looser using a special library for this thing, I just need to make it by myself!
import socket
servername = 'google.com'
serverport = 80
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sentence = 'GET / HTTP/1.1\nHost: google.com\nConnection: close'.format(servername)
print(sentence)
clientsocket.connect((servername, serverport))
clientsocket.send(sentence.encode())
new_sentence = clientsocket.recv(1024)
print('from server: {}'.format(new_sentence.decode()))
clientsocket.close()
I've tried different approaches of code, but all at all it should looks like this as far as I understand, what is the problem? Why it doesn't work?
Upvotes: 1
Views: 1642
Reputation: 23
import socket
servername = 'google.com'
serverport = 80
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sentence = '''GET / HTTP/1.1
Host: {}
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US;q=0.5,en;q=0.3
Connection: close
'''.format(servername)
print(sentence)
clientsocket.connect((servername, serverport))
clientsocket.send(sentence.encode())
new_sentence = clientsocket.recv(1024)
print('from server: {}'.format(new_sentence.decode()))
clientsocket.close()
Upvotes: 0
Reputation: 7812
You don't recieve response from server, cause it still wait data from you. In HTTP protocol you should send \r\n\r\n
(CRLF CRLF) to inform server about end of request headers.
CRLF = '\r\n'
sentence = CRLF.join(['GET / HTTP/1.1', 'Host: ' + servername, 'Connection: close', '', ''])
Upvotes: 3