无法发送JSON作为GO中的HTTP POST请求的主体,总是返回400错误和5035代码?

问题描述 投票:0回答:1

我想将JSON HTTP请求发送到API,但是它返回错误400 Bad Request和5035代码(无效的表单主体)。我需要帮助解决此问题!那是我的代码:

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", "[email protected]", "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))
}

输出:

{“ message”:“无效的表单正文”,“ code”:50035}


状态码:

400错误的请求


json http go post
1个回答
0
投票

这里是我为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
}
© www.soinside.com 2019 - 2024. All rights reserved.