每次我尝试拉google.com时,它都会以400错误的请求响应。尝试将\ n \ n更改为\ r \ n,但仍然存在相同的问题。由于它的HTTP错误,我认为套接字没有问题。
import socket
import ssl
socks = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
SSLSocks = ssl.wrap_socket(socks)
ip = socket.gethostbyname('google.com')
request = "GET / HTTPS/1.1\n"
request += "Host: " + ip + "\n\n"
#request += "Content-Type: application/json\r\n"
#request += "Connection: close"+"\r\n"
SSLSocks.connect((ip,443))
SSLSocks.send(request.encode())
result = SSLSocks.recv(4096)
print(ip)
print(result)
输出:
172.217.163.142
b'HTTP/1.0 400 Bad Request\r\nContent-Type: text/html; charset=UTF-8\r\nReferrer-Policy: no-referrer\r\nContent-Length: 1555\r\nDate: Tue, 22 Jan 2019 12:28:37 GMT\r\n\r\n<!DOCTYPE html>\n<html lang=en>\n <meta charset=utf-8>\n <meta name=viewport content="initial-scale=1, minimum-scale=1, width=device-width">\n <title>Error 400 (Bad Request)!!1</title>\n <style>\n *{margin:0;padding:0}html,code{font:15px/22px arial,sans-serif}html{background:#fff;color:#222;padding:15px}body{margin:7% auto 0;max-width:390px;min-height:180px;padding:30px 0 15px}* > body{background:url(//www.google.com/images/errors/robot.png) 100% 5px no-repeat;padding-right:205px}p{margin:11px 0 22px;overflow:hidden}ins{color:#777;text-decoration:none}a img{border:0}@media screen and (max-width:772px){body{background:none;margin-top:0;max-width:none;padding-right:0}}#logo{background:url(//www.google.com/images/branding/googlelogo/1x/googlelogo_color_150x54dp.png) no-repeat;margin-left:-5px}@media only screen and (min-resolution:192dpi){#logo{background:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) no-repeat 0% 0%/100% 100%;-moz-border-image:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) 0}}@media only screen and (-webkit-min-device-pixel-ratio:2){#logo{background:url(//www.google.com/images/br'
答案 0 :(得分:2)
修复代码:
HTTP
\r\n
结束每一行上下文管理器也有很大帮助,而且似乎主要由micropython支持
import socket
import ssl
host = 'www.google.com'
request = "GET / HTTP/1.1\r\n"
request += "Host: " + host + "\r\n"
request += "Content-Type: application/json\r\n"
request += "Connection: close\r\n"
request += "\r\n"
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock = ssl.wrap_socket(sock)
sock.connect((host, 443))
peer = sock.getpeername()
sock.send(request.encode())
result = sock.recv(4096)
sock.close()
print(peer)
print(result)