dsieyx2015 2016-12-09 21:07
浏览 384
已采纳

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

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 := "BTC_ETH"
depth := 20
reqURL := "https://poloniex.com/public?command=returnOrderBook"
values := url.Values { "currencyPair": []string{pair}, "depth": []string{depth}}
fmt.Printf("
 Values = %s
", values.Encode())        //DEBUG
req, err := http.NewRequest("GET", reqURL, strings.NewReader(values.Encode()))
fmt.Printf("
REQUEST = %+v
", req)                   //DEBUG
resp, err := api.client.Do(req)
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
fmt.Printf("
REST CALL RETURNED: %X
",body)          //DEBUG

My DEBUG print statements print out the following:

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."}

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 + "&" + 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&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: *way too long, just assume it'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条回答 默认 最新

  • drf97973 2016-12-09 21:16
    关注

    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 := "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 only errors on bad methods or un-parsable urls
    }
    

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 像这种代码要怎么跑起来?
  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件