尝试在Go中完成HTTP帖子:
发布到: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)
}
答案 0 :(得分:2)
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)
}
这样的事可能有用。但正如我在评论中已经说过的那样,你应该多熟悉一下这种语言。发布代码时,请确保编译。