简体   繁体   中英

Raw HTTP client not returning any data

import socket

host = 'www.google.com'
port = 80

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)


try :
    client.connect((host, port))
except socket.error:
    print ("Err")

package = '00101'

package.encode('utf-8')


client.sendall(package.encode(encoding = 'utf-8'))

response = client.recv(4096)


print (response.decode('UTF-8')

I kept getting b'' as my return, so I'm trying to decode it. The error I receive is unexpected EOF while parsing. Should I not include the decoding() function in my printing? I've tried printing only response, the .decode() function did not decode. What should I try?

You need to send a valid HTTP request. For example:

package = b'''GET /HTTP/1.1
Host: www.google.com

'''

client.sendall(package)

Which correctly returns a redirect on my machine. Note the empty line at the end of package , which ends the request.

When you send b'00101' and start reading, the google server has not yet processed your request and returns nothing. By sending a trailing newline ( package = b'00101\\n' ) it will start processing your request, and you will get:

...
<p>Your client has issued a malformed or illegal request.  <ins>That’s all we know.</ins>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM