douwen5924 2015-02-04 09:57
浏览 7
已采纳

发送带有数据的请求

I'm trying to access an API like this:

package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "net/http"
    "net/url"
)

func main() {
    apiUrl := "https://example.com/api/"
    data := url.Values{}
    data.Set("api_token", "MY_KEY")
    data.Add("action", "list_projects")
    req, _ := http.NewRequest("POST", apiUrl, bytes.NewBufferString(data.Encode()))
    client := &http.Client{}
    resp, err := client.Do(req)
    defer resp.Body.Close()
    if err == nil {
        body, _ := ioutil.ReadAll(resp.Body)
        fmt.Println(resp.Status)
        fmt.Println(string(body))
    }
}

But the response from an API tells me there was no data in POST request.

If I do it like this with curl, it works:

$ curl -X POST "https://example.com/api/" -d "api_token=MY_KEY" -d "action=list_projects"
  • 写回答

1条回答 默认 最新

  • dongou2019 2015-02-04 10:41
    关注

    You may want to use this form of request

    resp, err := http.PostForm("http://example.com/form", 
                                url.Values{"key": {"Value"}, "id": {"123"}})
    

    or use the right mime type :

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

    and encode data

    strings.NewReader(data.Encode())
    

    It's better if you test err != nil and return if necessary. This code may not work cause the request failed.

    defer resp.Body.Close()
    

    instead use this pattern:

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer resp.Body.Close()
    body, _ := ioutil.ReadAll(resp.Body)
    fmt.Println(resp.Status)
    fmt.Println(string(body))
    

    So you can see in the console if the request failed or not

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 flask实现搜索框访问数据库
  • ¥15 mrk3399刷完安卓11后投屏调试只能显示一个设备
  • ¥20 白日门传奇少一个启动区服和启动服务器的快捷键,东西都是全的 , 他们说套一个出来就行了 但我就是弄不好,谁看看,
  • ¥100 如何用js写一个游戏云存档
  • ¥15 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数