V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
ropon
V2EX  ›  Go 编程语言

net/http 返回状态码是非 200 获取响应体疑问

  •  
  •   ropon ·
    ropon · 2020-06-17 16:20:57 +08:00 · 1306 次点击
    这是一个创建于 1417 天前的主题,其中的信息可能已经有所发展或是发生改变。

    net/http 包请求一个 URL 地址,返回状态码是非 200,比如 400,如何获取响应体的内容呢?

    测试结果:

    • 使用 postman 、Python requests 库获取内容
    {
        "errcode": 4023,
        "errmsg": "认证失败"
    }
    
    • 使用 go net/http 包 获取内容
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
    <title>400 Bad Request</title>
    <h1>Bad Request</h1>
    <p>The browser (or proxy) sent a request that this server could not understand.</p>
    

    net/http 包是否状态码 200 才读响应体的内容呢?

    5 条回复    2020-06-18 14:36:28 +08:00
    CEBBCAT
        1
    CEBBCAT  
       2020-06-17 16:40:27 +08:00
    net/http 只有在 err 不为 nil 时才不可以读取 resp.Body,底下那个就是 server 返回的消息体。

    你可以使用 netcat 监听本地一个端口,对比 postman 或 rewuests 的请求与 net/http 的请求有什么差异。

    上面那个是 JSON,底下那个看着像是 HTTP 服务器默认的错误页面。所以你确认 postman 和 go 代码测试的是同一个服务器吗? postman 那个也是 400 错误吗?

    你需要补一点 HTTP 特别是 TCP 基础,这样你就明白无论什么 postman 还是 requests 都可以通过 telnet 来替代。

    以及你八成还要学学《提问的智慧》,若是可以,还可以搜搜 coolshell 的『 XY 问题』
    Vegetable
        2
    Vegetable  
       2020-06-17 16:42:32 +08:00
    不对的,你两个请求返回内容不一样。
    后边的 html 就是 body,显然不是你说的 json,应该是请求的部分错了。
    CEBBCAT
        3
    CEBBCAT  
       2020-06-17 16:53:27 +08:00
    看起来像是个前辈……奇怪……
    ropon
        4
    ropon  
    OP
       2020-06-17 17:13:09 +08:00
    应该是程序问题( https://github.com/Ropon/newpanel ),新写一个 demo 又是对的。
    D:\Seafile\Go\src\test>gor
    {"errcode": 4025, "errmsg": "this is test"}
    ropon
        5
    ropon  
    OP
       2020-06-18 14:36:28 +08:00
    找到问题了,是这行引起的
    # api = Api(site_bp, default_mediatype="application/json;charset=utf-8")
    api = Api(site_bp)
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2483 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 12:19 · PVG 20:19 · LAX 05:19 · JFK 08:19
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.