doudi8519 2016-07-22 09:08 采纳率: 100%
浏览 2478
已采纳

如何设置像Java方法HttpPost.setEntity这样的HTTP Post实体?

我是一个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))
}

thank you all you guys.

  • 写回答

1条回答 默认 最新

  • dongyuling0312 2016-07-22 10:07
    关注

    I changed a bit code to use NewBufferString, and tested it together with server that prints request's body:

    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()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料