gpt4 book ai didi

python - 来自谷歌的 400 错误请求

转载 作者:可可西里 更新时间:2023-11-01 17:04:38 26 4
gpt4 key购买 nike

每次当我尝试拉取 google.com 时,它只会响应 400 Bad Request。尝试将\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'

最佳答案

修复代码:

  1. 协议(protocol)仍然是HTTP
  2. 你需要用\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)

关于python - 来自谷歌的 400 错误请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54308506/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com