0

我正在构建一个简单的 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。为什么会出错?我该如何解决。

4

1 回答 1

0

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

    content_len = int(self.headers.getheader('content-length', 0))
    post_body = self.rfile.read(content_len)
于 2017-04-17T15:22:23.373 回答