2016-07-22 80 views
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)) 
} 

謝謝大家你們。

+1

這對我的作品。我能夠在本地運行https://play.golang.org/p/cQmGVyelZu(注意Playground禁用HTTP)並獲取https://requestb.in/176m02c1?inspect –

+0

Carletti,感謝您的回答,問題是發現,因爲我們的服務器是讀取表單值而不是請求體。非常感謝您的幫助。:) –

回答

1

我改了一下代碼使用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() 
} 
+0

嘿! @ plutov,謝謝我解決了這個問題。謝謝你的重播。 –