'golang, post with json fails, but multipart succeed
When I tried to send post with json, 401 error (unauthorized messages) showed. But with multipart, then succeeded.
In the following code,
I could get the token with only requestTokenByBuff which includes multipart.
Everytime I send post with json, I got failed. I tried to print json body, and there was no error. No header with body also made same result(401 error). I did not test http.Post because Header should be inputed.
Why does post with json fail?
type AuthConfig struct {
ClientId string `json:"client_id"`
ClientSecret string `json:"client_secret"`
Code string `json:"data"`
GrantType string `json:"grant_type"`
}
var host string
func initAuthConfig(a *AuthConfig) {
host = "https://xxxxxxx"
a.ClientId = "xxxxxxx"
a.ClientSecret = "xxxxxxx"
a.Code = "xxxxx"
a.GrantType = "xxxx"
}
func initAuthConfig2() {
host = "https://xxxxxxx"
}
func requestToken(auth *AuthConfig) {
authbytes, _ := json.Marshal(auth)
authbuff := bytes.NewBuffer(authbytes)
client := &http.Client{}
req, err := http.NewRequest("POST", host, authbuff)
if err != nil {
log.Fatalln(err)
}
req.Header.Add("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.xxxxxx")
req.Header.Add("Cookie", "SCOUTER=xxxxxxx")
req.Header.Add("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
log.Fatalln(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalln(err)
}
data := string(body)
fmt.Println(data)
}
func requestTokenByBuff(buff *bytes.Buffer) {
writer := multipart.NewWriter(buff)
_ = writer.WriteField("client_id", "xxxxxxxxxx")
_ = writer.WriteField("client_secret", "xxxxxxxx")
_ = writer.WriteField("data", "xxxxxx")
_ = writer.WriteField("grant_type", "xxxxxxx")
err := writer.Close()
if err != nil {
log.Fatalln(err)
return
}
client := &http.Client{}
req, err := http.NewRequest("POST", host, buff)
if err != nil {
log.Fatalln(err)
}
req.Header.Add("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.xxxx")
req.Header.Add("Cookie", "SCOUTER=xxxxxxxx")
req.Header.Set("Content-Type", writer.FormDataContentType())
resp, err := client.Do(req)
if err != nil {
log.Fatalln(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalln(err)
}
data := string(body)
fmt.Println(data)
}
func main() {
// config := new(AuthConfig)
// initAuthConfig(config)
// requestToken(config)
buff := &bytes.Buffer{}
initAuthConfig2()
requestTokenByBuff(buff)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
