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 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类