我正在构建一个简单的Python工具,它通过COM端口从外部接收器获取GPS坐标,并将其转换为Google Geolocation API返回的JSON字符串。目的是将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请求时,它工作正常,但是当请求是浏览器发送的请求时(即正文中的#39; {}') :
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。为什么会出错?我该如何解决呢?
答案 0 :(得分:0)
我能想到的最好的是我需要对发布的内容做些什么,所以我只是将这两行添加到do_POST
处理程序的开头:
content_len = int(self.headers.getheader('content-length', 0))
post_body = self.rfile.read(content_len)