V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
ropon

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

  •  
  •   ropon ·
    ropon · Jun 17, 2020 · 1691 views
    This topic created in 2153 days ago, the information mentioned may be changed or developed.

    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 replies    2020-06-18 14:36:28 +08:00
    CEBBCAT
        1
    CEBBCAT  
       Jun 17, 2020
    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  
       Jun 17, 2020
    不对的,你两个请求返回内容不一样。
    后边的 html 就是 body,显然不是你说的 json,应该是请求的部分错了。
    CEBBCAT
        3
    CEBBCAT  
       Jun 17, 2020
    看起来像是个前辈……奇怪……
    ropon
        4
    ropon  
    OP
       Jun 17, 2020
    应该是程序问题( https://github.com/Ropon/newpanel ),新写一个 demo 又是对的。
    D:\Seafile\Go\src\test>gor
    {"errcode": 4025, "errmsg": "this is test"}
    ropon
        5
    ropon  
    OP
       Jun 18, 2020
    找到问题了,是这行引起的
    # api = Api(site_bp, default_mediatype="application/json;charset=utf-8")
    api = Api(site_bp)
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2927 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 11:43 · PVG 19:43 · LAX 04:43 · JFK 07:43
    ♥ Do have faith in what you're doing.