【问题标题】:How to send post form data through a http client?如何通过 http 客户端发送表单数据?
【发布时间】:2020-08-18 15:11:34
【问题描述】:

我的 post 请求有问题,需要通过 http 客户端发送简单的表单数据。 http.PostForm() 不行,因为我需要设置自己的用户代理和其他标头。

这里是示例

func main() {
    formData := url.Values{
        "form1": {"value1"},
        "form2": {"value2"},
    }

    client := &http.Client{}
    
    //Not working, the post data is not a form
    req, err := http.NewRequest("POST", "http://test.local/api.php", strings.NewReader(formData.Encode()))
    if err != nil {
        log.Fatalln(err)
    }
    
    req.Header.Set("User-Agent", "Golang_Super_Bot/0.1")
    
    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)
    }
    
    log.Println(string(body))
}

【问题讨论】:

    标签: http go http-post


    【解决方案1】:

    您还需要将内容类型设置为application/x-www-form-urlencoded,这对应于Value.Encode()使用的编码。

    req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
    

    这是Client.PostForm 所做的事情之一。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多