2017-03-23 1 views
0

COM 포트를 통해 외부 수신기에서 GPS 좌표를 가져 와서 Google Geolocation API에서 반환하는 JSON 문자열로 변환하는 간단한 Python 도구를 작성합니다. 그 목적은 Firefox의 Google Geolocation 공급자 URL을이 문자열을 브라우저에 다시 제공하는 로컬 URL로 대체하여 브라우저에서 GPS 기반 위치를 구현하는 것입니다.BaseHTTPServer POST 요청 - 연결 재설정

GPS 부분은 괜찮지 만 HTTP 서버가 브라우저에 데이터를 전송하는 데 문제가 있습니다. 브라우저 Google에서 위치를 요청하면,이 같은 POST를 보냅니다 : 나는 컬에서 POST 요청을 보낼 때

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() 

그래서 잘 작동 :

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 

{} 

이 그것에 응답하는 내 코드입니다 즉, 빈,하지만 요청 (본문에 즉 '{}')가 브라우저에서 보낸입니다하지 않을 때 :

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

의 I 내가 게시 된 내용으로 뭔가를 할 필요가 있다는 것입니다 가지고 올 수 있었던 가장, 그래서 난 그냥 do_POST 핸들러의 시작 부분에 다음 두 줄을 추가 :

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