dpdrtj1075 2014-07-11 04:03
浏览 5
已采纳

转到:使用有效负载/正文发布

Trying to accomplish a HTTP Post in Go:

Posting to: apiUrl

Payload/Post Body (expected as a json string): postBody

Here is the error I'm getting:

cannot use postBodyJson (type []byte) as type io.Reader in argument to http.Post: 
    []byte does not implement io.Reader (missing Read method)

What am I doing wrong?

Code:

package main

import (
    "encoding/json"
    "fmt"
    "net/http"
)

func main() {
    var postBody = []string{
        "http://google.com",
        "http://facebook.com",
        "http://youtube.com",
        "http://yahoo.com",
        "http://twitter.com",
        "http://live.com",
    }
    requestUrl := "http://lsapi.seomoz.com/linkscape/url-metrics"

    postBodyJson, _ := json.Marshal(postBody)

    resp, err := http.Post(requestUrl, "application/json", postBodyJson)
    fmt.Println(resp)
}
  • 写回答

1条回答 默认 最新

  • duancao2082 2014-07-11 08:44
    关注
    package main
    
    import (
        "bytes"
        "encoding/json"
        "fmt"
        "log"
        "net/http"
    )
    
    func main() {
        var postBody = []string{
            "http://google.com",
            "http://facebook.com",
            "http://youtube.com",
            "http://yahoo.com",
            "http://twitter.com",
            "http://live.com",
        }
        apiUrl := "http://lsapi.seomoz.com/linkscape/url-metrics"
    
        buf := bytes.NewBuffer(nil)
        enc := json.NewEncoder(buf)
        err := enc.Encode(postBody)
        if err != nil {
            log.Fatal(err)
        }
        resp, err := http.Post(apiUrl, "application/json", buf)
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(resp)
    }
    

    Something like this might work. But as I already said in the comments, you should familiarize yourself with the language a little more. When you post code, make sure it compiles.

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

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)