英文:
Golang OData Request via net/http package
问题
我正在尝试向一个测试的OData服务器发送请求。我尝试了这个https://www.postman.com/collections/bf7d9130241aaa7160d8集合中的大多数端点。然而,当我使用net/http包发送请求时,一些端点返回错误。可能的原因是端点字符串中的空格。使用golang发送请求到这个端点的正确方法是什么?
我的代码:
import (
"fmt"
"io/ioutil"
"log"
"net/http"
)
func main() {
resp, err := http.Get("http://services.odata.org/V4/TripPinService/People?$filter=FirstName eq 'Vincent'")
if err != nil {
log.Fatalln(err)
}
if resp.StatusCode != 200 {
log.Fatalln(resp.Status)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalln(err)
}
sb := string(body)
fmt.Println(sb)
}
返回"400 Bad Request"。
英文:
I am trying to send request to a test OData server. I tried to most of endpoints in this https://www.postman.com/collections/bf7d9130241aaa7160d8 collection. However some of endpoints return error when I sent request with net/http package. Probably the reason is about endpoint string spaces. What is the correct way to send request to this endpoint with golang.
my code:
import (
"fmt"
"io/ioutil"
"log"
"net/http"
)
func main() {
resp, err := http.Get("http://services.odata.org/V4/TripPinService/People?$filter=FirstName eq 'Vincent'")
if err != nil {
log.Fatalln(err)
}
if resp.StatusCode != 200 {
log.Fatalln(resp.Status)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalln(err)
}
sb := string(body)
fmt.Println(sb)
}
Returns "400 Bad Request"
答案1
得分: 2
尝试使用net/url
包中的url
包的Values
和Encode
方法。
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
)
func main() {
baseURL := "http://services.odata.org/V4/TripPinService/People"
v := url.Values{}
v.Set("$filter", "FirstName eq 'Vincent'")
requestURL := baseURL + "?" + v.Encode() // 将它们组合在一起
resp, err := http.Get(requestURL)
if err != nil {
log.Fatalln(err)
}
if resp.StatusCode != 200 {
log.Fatalln(resp.Status)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalln(err)
}
sb := string(body)
fmt.Println(sb)
}
资源:
英文:
Try to use url
package's Values
and Encode
method from net/url
package.
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
)
func main() {
baseURL := "http://services.odata.org/V4/TripPinService/People"
v := url.Values{}
v.Set("$filter", "FirstName eq 'Vincent'")
requestURL := baseURL + "?" + v.Encode() // put it all together
resp, err := http.Get(requestURL)
if err != nil {
log.Fatalln(err)
}
if resp.StatusCode != 200 {
log.Fatalln(resp.Status)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalln(err)
}
sb := string(body)
fmt.Println(sb)
}
Resources:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论