简体   繁体   中英

Unable to send JSON as body for HTTP POST request in GO Alwayes return 400 Error and 5035 Code?

I want to send JSON HTTP Request to an API but it returns error 400 Bad Request and 5035 Code (Invalid Form Body). I need help to fix this! that's my code:

func creator() {

    api := "https://discordapp.com/api/v6/auth/register"

    //adding the Transport object to the http Client
    client := &http.Client{
        Timeout: time.Second * 5,
    }

    username, email, password := "Alpha", "Aplhpax@gmail.com", "Alpha123"


    url, err := url.Parse(api)
    if err != nil {
        fmt.Println(err)
    }



    body := []byte(`{"fingerprint":"` + "3s5dfsdf5461sdfaFD2hfd" + `","email":"` + email + `","username":"` + username + `","password":"` + password + `"}`)

    req, err := http.NewRequest("POST", url.String(), bytes.NewBuffer(body))

    if err != nil {
        fmt.Println(err)
    }
    req.Header.Set("Accept", "*/*")
    req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36")

    resp, err := client.Do(req)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(resp.Status)
    //getting the response
    data, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(string(data))
}

Output:

{"message": "Invalid Form Body", "code": 50035}


Status code:

400 Bad Request


Here is a sample of a form post I did for the SonarCloud API.

// Create Project(Project)
//   Create a new SonarCloud project usinig p
//   Note SonarCloud expects application/x-www-form-urlencoded
func (c *SonarCloudClient) CreateProject(p NewProject) (*http.Response, error) {

    data := url.Values{}
    data.Set("name", p.Name)

    // Project names for none default organization are global
    // Add a prefix to avoid naming conflicts
    // TODO: Make this configurable by the end user
    data.Set("project", KeyPrefix+p.Project)
    data.Set("organization", p.Organization)
    data.Set("visibility", p.Visibility)

    url := c.URI + ProjectCreate
    req, err := http.NewRequest("POST", url, strings.NewReader(data.Encode()))
    if err != nil {
        return HandleHTTPClientError(nil, err)
    }

    req.Header.Add(contentType, wwwForm)
    req.Header.Add(contentLength, strconv.Itoa(len(data.Encode())))
    rsp, err := c.Client.Do(req)

    if err != nil {
        return HandleHTTPClientError(rsp, err)
    }

    if rsp.StatusCode == 400 {
        errmsg, _ := ioutil.ReadAll(rsp.Body)
        return rsp, errors.New(string(errmsg))
    }

    return rsp, nil
}

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