【问题标题】:calling api in golang error 400 bad request在golang错误400错误请求中调用api
【发布时间】:2018-08-19 11:30:50
【问题描述】:

我收到以下错误。下面用 golang 编写的代码有什么问题?有什么想法吗?

&{400 错误请求 400 HTTP/1.1 1 1 map[Content-Type:[text/html; charset=us-ascii] 日期:[2018 年 8 月 15 日星期三 16:14:34 GMT] 内容长度:[311]] 0xc42005c280 311 [] true false map[] 0xc4200fe000 0xc4200a62c0}


url := fmt.Sprintf("https://api.labs.cognitive.microsoft.com/academic/v1.0/interpret?query=a two level microprogram simulator&complete=0&count=10&model=latest")

【问题讨论】:

    标签: go microsoft-cognitive


    【解决方案1】:

    虽然 Go 代码有问题(my-key 看起来特别奇怪),但问题是您需要转义查询参数中的空格:

    $ curl 'https://api.labs.cognitive.microsoft.com/academic/v1.0/interpret?query=a two level microprogram simulator&complete=0&count=10&model=latest'
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
    <HTML><HEAD><TITLE>Bad Request</TITLE>
    <META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
    <BODY><h2>Bad Request</h2>
    <hr><p>HTTP Error 400. The request is badly formed.</p>
    </BODY></HTML>
    

    使用%20 转义空格后,我们得到预期的访问错误:

    $ curl 'https://api.labs.cognitive.microsoft.com/academic/v1.0/interpret?query=a%20two%20level%20microprogram%20simulator&complete=0&count=10&model=latest'
    
    {"error":{"code":"Unspecified","message":"Access denied due to invalid subscription key. Make sure you are subscribed to an API you are trying to call and provide the right key."}}
    

    最好让 Go 来处理:

    import "net/url"
    
    base_url := "https://api.labs.cognitive.microsoft.com/academic/v1.0/interpret"
    
    var v url.Values
    v.Add("query", "a two level microprogram simulator")
    v.Add("complete", "0")
    v.Add("count", "10")
    v.Add("model", "latest")
    
    url := base_url + "?" + v.Encode()
    

    【讨论】:

      【解决方案2】:

      其实我之前也想通了。所以我的建议是简单地添加 fol url.QueryEscape("一个二级微程序模拟器")

      【讨论】:

        猜你喜欢
        • 2018-11-20
        • 2022-01-04
        • 1970-01-01
        • 2021-08-16
        • 2018-05-10
        • 1970-01-01
        • 1970-01-01
        • 2020-11-13
        • 2011-06-18
        相关资源
        最近更新 更多