0
我是一个新的golang程序员。在java中,使用方法HTTP.setEntity()很容易设置。但在golang中,我有测试servel的方式来设置它,但我们的服务器仍然缺少接收实体数据。 这里是代码:如何设置HTTP Post实体像Java的方法HttpPost.setEntity
func bathPostDefects(){
url := "http://127.0.0.1/edit"
var jsonStr = []byte(`{"key":"abc","id":"110175653","resolve":2,"online_time":"2016-7-22","priority":1,"comment":"something.."}`)
req, err := http.NewRequest("POST",url,bytes.NewBuffer(jsonStr))
fmt.Println("ContentLength: ",len(jsonStr))
req.Header.Set("Content-Type","application/json")
req.Header.Set("Content-Length",string(len(jsonStr)))
client := &http.Client{}
resp,err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println("response Status:", resp.Status)
fmt.Println("response Headers:", resp.Header)
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("response Body:", string(body))
}
问题找到了,这是导致我们的servlet已经阅读形式的值,而不是请求体,代码更新如下:
func bathPostDefects(){
v := url.Values{}
v.Set("key", "abc")
v.Add("id", "110175653")
v.Add("resolve", "2")
v.Add("online_time", "2016-7-22")
v.Add("priority", "1")
v.Add("comment", "something..")
fmt.Println(v.Get("id"))
fmt.Println(v.Get("comment"))
resp, err := http.PostForm("http://127.0.0.1/edit",v)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println("response Status:", resp.Status)
fmt.Println("response Headers:", resp.Header)
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("response Body:", string(body))
}
谢谢大家你们。
这对我的作品。我能够在本地运行https://play.golang.org/p/cQmGVyelZu(注意Playground禁用HTTP)并获取https://requestb.in/176m02c1?inspect –
Carletti,感谢您的回答,问题是发现,因为我们的服务器是读取表单值而不是请求体。非常感谢您的帮助。:) –