gpt4 book ai didi

go - 如何设置 HTTP Post 实体,如 Java 的方法 HttpPost.setEntity

转载 作者:数据小太阳 更新时间:2023-10-29 03:15:01 27 4
gpt4 key购买 nike

我是一名新的 golang 程序员。在 java 中,使用 HTTP.setEntity() 方法很容易设置。但在 golang 中,我有测试服务器的方式来设置它,但我们的服务器仍然缺少接收实体数据。这是代码:

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))
}

谢谢大家。

最佳答案

我更改了一些代码以使用 NewBufferString,并与打印请求正文的服务器一起对其进行了测试:

package main

import (
"bytes"
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
)

func bathPostDefects() {
url := "http://127.0.0.1:4141/"
var jsonStr = `{"key":"abc","id":"110175653","resolve":2,"online_time":"2016-7-22","priority":1,"comment":"something.."}`
req, err := http.NewRequest("POST", url, bytes.NewBufferString(jsonStr))
fmt.Println("ContentLength: ", len(jsonStr))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Content-Length", string(len(jsonStr)))
client := &http.Client{}
_, err = client.Do(req)
if err != nil {
panic(err)
}
}

func server() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
body, _ := ioutil.ReadAll(r.Body)
fmt.Println("Body: ", string(body))
})

log.Fatal(http.ListenAndServe(":4141", nil))
}
func main() {
go server()
time.Sleep(time.Second)

bathPostDefects()
}

关于go - 如何设置 HTTP Post 实体,如 Java 的方法 HttpPost.setEntity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38522504/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com