doucaishou0074 2014-06-15 14:20
浏览 35
已采纳

使用基本auth和formvalue进行Http Post请求

I am writing a wrapper for an API in go. The api uses basic auth and then POST request requires PostForm value. I'm doing something like this:

func NewFoo(name string) string {
    client := &http.Client{}
    URL := HOST + "foo/"
    req, err := http.NewRequest("POST", URL, nil)
    v := url.Values{}
    v.Set("name", name)
    req.Form = v
    req.SetBasicAuth(EMAIL, PASSWORD)
    resp, err := client.Do(req)
    if err != nil {
        log.Fatal(err)
    }
    bodyText, err := ioutil.ReadAll(resp.Body)
    s := string(bodyText)
    return s
}

I had a similar, GET request without the form value and it works. When I run it, it tells me that the "name" value is required. (so it's not getting it)

Is there any reason this does not work?

  • 写回答

1条回答 默认 最新

  • dongyanju1094 2014-06-15 14:49
    关注

    From http://golang.org/pkg/net/http/#Request

    // Form contains the parsed form data, including both the URL
    // field's query parameters and the POST or PUT form data.
    // This field is only available after ParseForm is called.
    // The HTTP client ignores Form and uses Body instead.
    Form url.Values
    

    You have to pass your url.Values to the request's body instead.

    func NewFoo(name string) string {
        client := &http.Client{}
        URL := HOST + "foo/"
        v := url.Values{}
        v.Set("name", name)
        //pass the values to the request's body
        req, err := http.NewRequest("POST", URL, strings.NewReader(v.Encode()))
        req.SetBasicAuth(EMAIL, PASSWORD)
        resp, err := client.Do(req)
        if err != nil {
            log.Fatal(err)
        }
        bodyText, err := ioutil.ReadAll(resp.Body)
        s := string(bodyText)
        return s
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!