I’m trying to write a function that will make a (curl) POST request to a remote service. the data is sent NOT as a json string but rather as a string url params:
“param1=1¶m2=2…”
in PHP I do it like this:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($dataArray));
$result = curl_exec($ch);
in GO I tried copying examples from the internet, non of them work… looks like the params i’m sending aren’t really sent, or something gets lost because the service returns error that mandatory params are missing…
here’s my attempt:
url := "http://www.bla..com"
postData := strings.NewReader(
"¶m1=1"+
"¶m2=2")
req, err := http.NewRequest("POST", url, postData)
fmt.Println(req)
if err != nil {
panic(err)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println("response Status:", resp.Status)
fmt.Println("response Headers:", resp.Header)
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("response Body:", string(body))
this version seems to work, even though i have other issues somewhere and the response claims 1 of my params is wrong… however in postman i put the same params and it works…
apiUrl := "http://www.bla.com"
resource := "/Api/"
data := url.Values{}
data.Set("param1", "1")
data.Add("param2", "2")
u, _ := url.ParseRequestURI(apiUrl)
u.Path = resource
urlStr := fmt.Sprintf("%v", u)
client := &http.Client{}
r, _ := http.NewRequest("POST", urlStr, bytes.NewBufferString(data.Encode()))
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
resp, _ := client.Do(r)
fmt.Println()
fmt.Println("response Status:", resp.Status)
fmt.Println()
fmt.Println("response Headers:", resp.Header)
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println()
fmt.Println("response Body:", string(body))