简体   繁体   中英

Golang OData Request via net/http package

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"

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:

Values type

Values.Encode example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM