我正在构建一个简单的Python工具,通过COM端口从外部接收器获取GPS坐标,并将其转换为JSON字符串,如Google Geolocation API返回的。其目的是将Firefox中的Google地理定位提供程序URL替换为本地URL,以便将该字符串返回给浏览器,从而在我的浏览器中实现基于GPS的定位。
GPS部分没问题,但我在HTTP服务器上向浏览器发送数据时遇到了问题。当浏览器向Google请求定位时,它会发送一个类似如下的帖子:
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一点也不熟悉。为什么会出问题呢?我怎么才能修复它呢。
发布于 2017-04-17 23:22:23
我所能想到的最好的情况是,我需要对发布的内容做一些处理,所以我只在do_POST处理程序的开头添加了这两行:
content_len = int(self.headers.getheader('content-length', 0))
post_body = self.rfile.read(content_len)https://stackoverflow.com/questions/42985862
复制相似问题