項目中須要用到Go語言,因此,快速學習了下,使用
net/http
庫寫了一個發送json數據的POST請求。json
示例:app
package main import ( "bytes" "fmt" "io/ioutil" "net/http" ) func main() { url := "http://baidu.com" fmt.Println("URL:>", url) //登錄用戶名 usrId := "LaoWong" //登錄密碼 pwd := "pwd1234" //json序列化 post := "{ \"UserId\":\"" + usrId + "\",\"Password\":\"" + pwd + "\"}" fmt.Println(url, "post", post) var jsonStr = []byte(post) fmt.Println("jsonStr", jsonStr) fmt.Println("new_str", bytes.NewBuffer(jsonStr)) req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr)) // req.Header.Set("X-Custom-Header", "myvalue") req.Header.Set("Content-Type", "application/json") 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)) }
上邊就是一個完整的示例,咱們可使用 Go在線編輯器進行運行該代碼。編輯器