Golang的`http.NewRequest(method, url, body)`无法正确创建格式化的请求。

huangapple go评论76阅读模式
英文:

Golang 'http.NewRequest(method, url, body)' fails to create correctly formatted request

问题

我正在尝试向以下API发送GET请求:

https://poloniex.com/public?command=returnOrderBook

带有URL参数:

currencyPair=BTC_ETH
depth=20
--> &currencyPair=BTC_ETH&depth=20

我尝试设置并执行请求,代码如下(为简洁起见,我删除了错误检查部分):

pair := "BTC_ETH"
depth := 20
reqURL := "https://poloniex.com/public?command=returnOrderBook"
values := url.Values{"currencyPair": []string{pair}, "depth": []string{strconv.Itoa(depth)}}
fmt.Printf("\n Values = %s\n", values.Encode())        //DEBUG
req, err := http.NewRequest("GET", reqURL, strings.NewReader(values.Encode()))
fmt.Printf("\nREQUEST = %+v\n", req)                   //DEBUG
resp, err := api.client.Do(req)
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
fmt.Printf("\nREST CALL RETURNED: %X\n", body)          //DEBUG

我的DEBUG打印输出如下:

Values = currencyPair=BTC_ETH&depth=20

REQUEST = &{Method:GET URL:https://poloniex.com/public?command=returnOrderBook Proto:HTTP/1.1 ProtoMajor:1 ProtoMinor:1 Header:map[User-Agent:[Poloniex GO API Agent]] Body:{Reader:0xc82028e840} ContentLength:29 TransferEncoding:[] Close:false Host:poloniex.com Form:map[] PostForm:map[] MultipartForm:<nil> Trailer:map[] RemoteAddr: RequestURI: TLS:<nil> Cancel:<nil>}
    
REST CALL RETURNED: {"error":"Please specify a currency pair."}

通过使用Postman进行测试,我发现只有在未指定currencyPair参数(包括大小写错误)时,API才会返回此错误。我无法弄清楚为什么请求不包括我指定的URL参数,因为从我的调试打印语句中可以明显看出values.Encode()是正确的。请求中的内容长度与URL参数所需的字符(字节)数量相对应。

现在,经过一番尝试,我找到了一个解决方案。如果我将http.NewRequest()行替换为以下内容,它就可以工作:

req, err := http.NewRequest(HTTPType, reqURL + "&" + values.Encode(), nil)

然而,原始语句为什么不起作用真的让我困扰。

新的DEBUG输出如下:

Values = currencyPair=BTC_ETH&depth=20

REQUEST = &{Method:GET URL:https://poloniex.com/public?command=returnOrderBook&currencyPair=BTC_ETH&depth=5 Proto:HTTP/1.1 ProtoMajor:1 ProtoMinor:1 Header:map[User-Agent:[Poloniex GO API Agent]] Body:<nil> ContentLength:0 TransferEncoding:[] Close:false Host:poloniex.com Form:map[] PostForm:map[] MultipartForm:<nil> Trailer:map[] RemoteAddr: RequestURI: TLS:<nil> Cancel:<nil>}
    
REST CALL RETURNED: *太长了,假设它是正确的财务数据*

希望对我在原始语句中做错了什么能提供一些帮助。我在另一个带有URL参数的API端点中使用了相同的方法(原始语句),并且它正常工作。对于为什么在这种情况下它不起作用感到困惑。

英文:

I'm trying to send a GET request to the following api:

> https://poloniex.com/public?command=returnOrderBook

w/ URL parameters:

> currencyPair=BTC_ETH
> depth=20
> --> &currencyPair=BTC_ETH&depth=20

I try to setup and execute my request as so: (note I've removed error checking for brevity)

pair := &quot;BTC_ETH&quot;
depth := 20
reqURL := &quot;https://poloniex.com/public?command=returnOrderBook&quot;
values := url.Values { &quot;currencyPair&quot;: []string{pair}, &quot;depth&quot;: []string{depth}}
fmt.Printf(&quot;\n Values = %s\n&quot;, values.Encode())        //DEBUG
req, err := http.NewRequest(&quot;GET&quot;, reqURL, strings.NewReader(values.Encode()))
fmt.Printf(&quot;\nREQUEST = %+v\n&quot;, req)                   //DEBUG
resp, err := api.client.Do(req)
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
fmt.Printf(&quot;\nREST CALL RETURNED: %X\n&quot;,body)          //DEBUG

My DEBUG print statements print out the following:

Values = currencyPair=BTC_ETH&amp;depth=20

REQUEST = &amp;{Method:GET URL:https://poloniex.com/public?command=returnOrderBook Proto:HTTP/1.1 ProtoMajor:1 ProtoMinor:1 Header:map[User-Agent:[Poloniex GO API Agent]] Body:{Reader:0xc82028e840} ContentLength:29 TransferEncoding:[] Close:false Host:poloniex.com Form:map[] PostForm:map[] MultipartForm:&lt;nil&gt; Trailer:map[] RemoteAddr: RequestURI: TLS:&lt;nil&gt; Cancel:&lt;nil&gt;}

REST CALL RETURNED: {&quot;error&quot;:&quot;Please specify a currency pair.&quot;}

Playing around with Postman I figured out the API only returns this error when the currencyPair parameter is not specified (including miscapitalized). I can't figure out why the request doesn't include the URL parameters I specified as it's obvious from my debug print statements that the values.Encode() is correct. The content length in the request corresponds to the right amount of chars (bytes) needed for URL parameters.

Now after playing around a bit I found a solution.
If I replace the http.NewRequest() line with the following it works:

req, err := http.NewRequest(HTTPType, reqURL + &quot;&amp;&quot; + values.Encode(), nil)

However, it's really bothering me why the original statement doesn't work.

The new DEBUG output is:

Values = currencyPair=BTC_ETH&amp;depth=20

REQUEST = &amp;{Method:GET URL:https://poloniex.com/public?command=returnOrderBook&amp;currencyPair=BTC_ETH&amp;depth=5 Proto:HTTP/1.1 ProtoMajor:1 ProtoMinor:1 Header:map[User-Agent:[Poloniex GO API Agent]] Body:&lt;nil&gt; ContentLength:0 TransferEncoding:[] Close:false Host:poloniex.com Form:map[] PostForm:map[] MultipartForm:&lt;nil&gt; Trailer:map[] RemoteAddr: RequestURI: TLS:&lt;nil&gt; Cancel:&lt;nil&gt;}

REST CALL RETURNED: *way too long, just assume it&#39;s the correct financial data*

Would love some input on what I did wrong in the original statement. I used the same method (original) for a different api endpoint w/ URL parameters and it worked fine. Confused on why it didn't work in this case.

答案1

得分: 5

GET请求不应包含请求体。相反,您需要将表单放入查询字符串中。

以下是正确的方法,不需要使用拼接字符串的技巧:

reqURL := "https://poloniex.com/public"
values := url.Values{"currencyPair": []string{pair}, "depth": []string{depth}}
values.Set("command", "returnOrderBook")
uri, _ := url.Parse(reqURL)
uri.Query = values.Encode()
reqURL = uri.String()
fmt.Println(reqURL)

req, err := http.NewRequest("GET", reqURL, nil)
if err != nil {
    panic(err) // NewRequest只会在方法错误或无法解析的URL时出错
}

这里是一个示例链接。

英文:

GET requests should not contain a body. Instead, you need to put the form into the query string.

Here's the proper way to do that, without hacky string concatenation:

reqURL := &quot;https://poloniex.com/public&quot;
values := url.Values { &quot;currencyPair&quot;: []string{pair}, &quot;depth&quot;: []string{depth}}
values.Set(&quot;command&quot;, &quot;returnOrderBook&quot;)
uri, _ := url.Parse(reqURL)
uri.Query = values.Encode()
reqURL = uri.String()
fmt.Println(reqURL)

req, err := http.NewRequest(&quot;GET&quot;, reqURL, nil)
if err != nil {
    panic(err) // NewRequest only errors on bad methods or un-parsable urls
}

https://play.golang.org/p/ZCLUu7UgZL

huangapple
  • 本文由 发表于 2016年12月10日 05:07:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/41068906.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定