[英]Python HTTPServer responding to curl but not to Postman GET request
Consider a simple server in Python3 with the module BaseHTTPRequestHandler
.考虑在 Python3 中使用
BaseHTTPRequestHandler
模块的简单服务器。
import json
import urllib.parse
from http.server import BaseHTTPRequestHandler, HTTPServer
import bson.json_util
class GetHandler(BaseHTTPRequestHandler):
def do_GET(self):
print("/n=================================")
json_string = '{"hello":"world"}'
self.wfile.write(json_string.encode())
self.send_response(200)
self.end_headers()
return
if __name__ == '__main__':
#from BaseHTTPServer import HTTPServer
server = HTTPServer(('localhost', 3030), GetHandler)
print ('Starting server, use <Ctrl-C> to stop')
server.serve_forever()
This is responding correctly with curl
from the Terminal:这是从终端使用
curl
正确响应:
curl -i http://localhost:3030/
However when trying to send a request from Postman it is not responding.但是,当尝试从 Postman 发送请求时,它没有响应。 I tried the URL
localhost:3030/
, http://localhost:3030/
and also with the loopback address.我尝试了 URL
localhost:3030/
、 http://localhost:3030/
以及环回地址。
Why is that?这是为什么?
In all the examples I have seen it was not specifying the content type so I did the same way and seeing that curl
worked I did not worry too much.在我所看到的所有示例中,它都没有指定内容类型,所以我以同样的方式做了,看到
curl
起作用了,我并没有太担心。
However content type should be specified: adding these lines before self.wfile.write(...)
solves the problem:但是应该指定内容类型:在
self.wfile.write(...)
之前添加这些行可以解决问题:
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
Please note that actually self.send_response(200)
has been moved, not added.请注意,实际上
self.send_response(200)
已被移动,而不是添加。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.