BaseHTTPServer POST请求连接Res

2024-04-18 23:24:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在构建一个简单的Python工具,它通过COM端口从外部接收器获取GPS坐标,并将其转换为类似googlegeolocationapi返回的JSON字符串。目的是将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

{}

这是我的回应代码:

^{pr2}$

因此,当我从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。为什么会出问题?我怎样才能修好它呢。在


Tags: comlocalhosthttpurldatawwwgoogle浏览器
1条回答
网友
1楼 · 发布于 2024-04-18 23:24:03

我所能想到的最好的方法就是我需要对发布的内容做些什么,所以我只在do_POST处理程序的开头添加了以下两行:

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

相关问题 更多 >