Created
February 22, 2016 01:04
-
-
Save 17twenty/2fb30a22141d84e52446 to your computer and use it in GitHub Desktop.
POST with NewRequest using Golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"fmt" | |
"io/ioutil" | |
"log" | |
"net/http" | |
"net/url" | |
) | |
const ( | |
clientSecret string = "9ca19353e1fb861f6d3aed8af6803c0b" | |
accessToken string = "d42cd44868d2fe953329677aa1c71e1d80f0f4d7" | |
siteHost string = "http://coop.apps.knpuniversity.com" | |
userID string = "460" | |
) | |
func main() { | |
client := &http.Client{} | |
data := url.Values{} | |
data.Set("client_id", `Lazy Test`) | |
data.Add("client_secret", clientSecret) | |
data.Add("grant_type", "client_credentials") | |
req, err := http.NewRequest("POST", fmt.Sprintf("%s/token", siteHost), bytes.NewBufferString(data.Encode())) | |
req.Header.Set("Content-Type", "application/x-www-form-urlencoded; param=value") // This makes it work | |
if err != nil { | |
log.Println(err) | |
} | |
resp, err := client.Do(req) | |
if err != nil { | |
log.Println(err) | |
} | |
f, err := ioutil.ReadAll(resp.Body) | |
if err != nil { | |
log.Println(err) | |
} | |
resp.Body.Close() | |
if err != nil { | |
log.Fatal(err) | |
} | |
fmt.Println(string(f)) | |
} |
Thank you
Yes, without Content-Type http.NewRequest('POST', url, body)
won't work....
Thank you!!
Very helpfull!
Thank you!!
Thanks
if post data has int type,the "data := url.Values{}" cannot be used
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you. 👍