尝试在 Go 中完成 HTTP Post:
发布到:apiUrl
Payload/Post Body(预期为 json 字符串):postBody
这是我遇到的错误:
cannot use postBodyJson (type []byte) as type io.Reader in argument to http.Post:
[]byte does not implement io.Reader (missing Read method)
我做错了什么?
代码:
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)
}
最佳答案
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)
}
这样的事情可能会奏效。但正如我在评论中所说的那样,你应该多熟悉一下这门语言。当您发布代码时,请确保它可以编译。
关于Go:使用有效负载/帖子正文发布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24689914/