英文:
Go: Posting with Payload/Post Body
问题
尝试在Go中进行HTTP Post请求:
请求地址:apiUrl
请求体(期望为JSON字符串):postBody
这是我得到的错误信息:
无法将postBodyJson(类型为[]byte)作为http.Post的参数类型io.Reader使用:
[]byte类型没有实现io.Reader(缺少Read方法)
我做错了什么?
代码:
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)
}
英文:
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
得分: 3
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)
}
类似这样的代码可能会起作用。但正如我在评论中已经提到的,你应该更加熟悉这门语言。在发布代码时,请确保它可以编译。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论