【问题标题】:Python HTTPServer responding to curl but not to Postman GET requestPython HTTPServer 响应 curl 但不响应 Postman GET 请求
【发布时间】:2019-04-01 17:54:37
【问题描述】:

考虑在 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()

这是来自终端的curl 正确响应:

curl -i http://localhost:3030/

但是,当尝试从 Postman 发送请求时,它没有响应。我尝试了 URL localhost:3030/http://localhost:3030/ 以及环回地址。

这是为什么呢?

【问题讨论】:

  • 我认为 curl 和 postman 有不同的用户代理,这可能会导致服务器响应方式的差异。还要检查 Postman 发送的是 GET 而不是 POST。
  • 您可以看到邮递员执行请求时使用的实际命令和正文。请在此处发布。
  • 我该怎么做?
  • 你能用 fiddler 之类的东西捕获这两个请求,看看有什么区别吗?

标签: python-3.x get postman httpserver


【解决方案1】:

在我看到的所有示例中,它都没有指定内容类型,所以我做了同样的事情,看到curl 有效,我并没有太担心。

但是应该指定内容类型:在self.wfile.write(...)之前添加这些行可以解决问题:

self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()

请注意,实际上self.send_response(200) 已被移动,而不是添加。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-30
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多