簡體   English   中英

Golang'http.NewRequest(method,url,body)'無法創建正確格式的請求

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

我正在嘗試將GET請求發送到以下api:

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

帶網址參數:

currencyPair = BTC_ETH
深度= 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{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."}

玩弄郵遞員,我發現只有在未指定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: *way too long, just assume it's the correct financial data*

希望對我在原始陳述中做錯的事情有所投入。 我對具有URL參數的不同api端點使用了相同的方法(原始),並且工作正常。 困惑為什么在這種情況下不起作用。

GET請求不應包含正文。 相反,您需要將表單放入查詢字符串中。

這是執行此操作的正確方法,而無需使用hacky字符串連接:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM