【问题标题】:BaseHTTPServer POST request - Connection ResetBaseHTTPServer POST 请求 - 连接重置
【发布时间】:2017-03-23 19:58:07
【问题描述】:

我正在构建一个简单的 Python 工具,该工具通过 COM 端口从外部接收器获取 GPS 坐标,并将其转换为 JSON 字符串,就像 Google Geolocation API 返回的那样。目的是将 Firefox 中的 Google Geolocation 提供程序 URL 替换为将这个字符串返回给浏​​览器的本地 URL,从而在我的浏览器中实现基于 GPS 的位置。

GPS 部分没问题,但我无法通过 HTTP 服务器将数据发送到浏览器。当浏览器向 Google 请求位置时,它会发送这样的 POST:

POST https://www.googleapis.com/geolocation/v1/geolocate?key=KEY HTTP/1.1
Host: www.googleapis.com
Connection: keep-alive
Content-Length: 2
Pragma: no-cache
Cache-Control: no-cache
Content-Type: application/json
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
Accept-Encoding: gzip, deflate, br

{}

这是我的回应代码:

from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer

PORT_NUMBER = 8080

class myHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        self.send_response(200)
        self.send_header('Content-type','application/json; charset=UTF-8')
        self.end_headers()
        self.wfile.write('{"location": {"lat": 33.333333, "lng": -33.333333}, "accuracy": 5}')
        return

try:
    server = HTTPServer(('', PORT_NUMBER), myHandler)
    print 'Started httpserver on port ', PORT_NUMBER
    server.serve_forever()

except KeyboardInterrupt:
    print 'Shutting down server'
    server.socket.close()

所以当我从 Curl 发送一个空的 POST 请求时它可以正常工作,但当请求是浏览器发送的请求时(即正文中的“{}”)则不行:

curl --data "{}" http://localhost:8080
> curl: (56) Recv failure: Connection was reset

curl --data "foo" http://localhost:8080
> curl: (56) Recv failure: Connection was reset

curl --data "" http://localhost:8080
> {"location": {"lat": 33.333333, "lng": -33.333333}, "accuracy": 5}

我根本不熟悉 HTTP 协议或 BaseHTTPServer。为什么会出错?我该如何解决它。

【问题讨论】:

    标签: python http basehttpserver basehttprequesthandler


    【解决方案1】:

    我能想到的最好的办法是我需要对发布的内容做一些事情,所以我只是将这两行添加到 do_POST 处理程序的开头:

        content_len = int(self.headers.getheader('content-length', 0))
        post_body = self.rfile.read(content_len)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多