BaseHTTPServer POST request - Connection Reset



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

GPS部分很好,但是我在使用HTTP服务器将数据发送到浏览器时遇到问题。当浏览器从谷歌请求位置时,它会发送如下 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。为什么会出错?我该如何解决它。

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

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

最新更新