问题描述
我需要向不符合规范的API发送未编码 GET请求。目标API不接受编码的URL,我只能按原样发送请求,而没有任何查询编码。默认情况下,net/http
对请求进行编码。我尝试过:
client := &http.Client{}
req,_ := http.NewRequest("GET",`https://api.website.com/rest/v1/item/0?search=[{"key":"tag","value":"myvalue"}]`,nil)
req.Header.Set("Authorization","Bearer " + viper.GetString("ACCESS_TOKEN"))
response,_ := client.Do(req)
defer req.Body.Close()
data,_ := ioutil.ReadAll(response.Body)
fmt.Printf("%s\n",data)
我尝试构建自己的Request
并操纵RawQuery
,但没有成功。我一直收到错误的请求,但是如果我通过Postman发送相同的请求,一切都很好。
编辑:这就是我自己尝试设置的URL,如果我打印它,我会看到它没有被编码。我得到的错误是:panic: runtime error: invalid memory address or nil pointer dereference
。
client := &http.Client{}
req,"",nil)
req.URL = &url.URL{
Host: "api.website.com",Scheme: "https",RawQuery: `/rest/v1/item/0?search=[{"key":"tag",}
req.Header.Set("Authorization","Bearer " + viper.GetString("RAINDROP_TOKEN"))
res,_ := ioutil.ReadAll(res.Body)
fmt.Printf("%s\n",data)
解决方法
在创建请求时指定协议和主机。将URL.Opaque设置为所需的请求URI:
req,_ := http.NewRequest("GET","https://api.website.com/",nil)
req.URL.Opaque = `/rest/v1/item/0?search=[{"key":"tag","value":"myvalue"}]`
req.Header.Set("Authorization","Bearer " + viper.GetString("RAINDROP_TOKEN"))
res,_ := client.Do(req)
defer req.Body.Close()
data,_ := ioutil.ReadAll(res.Body)