golang语言发送json格式的http请求
1、发送普通的GET请求
func testGet() {
url := "https://baidu.com"
req, err := http.NewRequest("GET", url, nil)
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))
}
返回结果:
response Status: 200 OK
response Headers: map[Content-Type:[text/html] Vary:[Accept-Encoding] ]
response Body: <!DOCTYPE html>
2、发送json为参数的post请求
可以直接用字符串拼写出json格式
func testPost(id int, name string) {
requestBody := fmt.Sprintf(`{
"id":%d",
"name": "%s"
}`, id, name)
var jsonStr = []byte(requestBody)
url := "https://test.com"
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
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))
}
也可以用struct进行转化,比如这样
type RequestBody struct {
Id int `json:"id"`
Name string `json:"name"`
}
func testPost(id int, name string) {
request := RequestBody{
Id: id,
Name: name,
}
requestBody := new(bytes.Buffer)
json.NewEncoder(requestBody).Encode(request)
url := "https://test.com"
req, err := http.NewRequest("POST", url, requestBody)
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))
}
3、对返回的json结果进行解析
同样是使用struct进行解析,例如返回的json为
{
"id": 1,
"name": "zhangsan"
}
则对应的代码为
type UserInfo struct {
Id string `json:"id"`
Name string `json:"name"`
}
func ParseResponse(input string) [] UserInfo {
var user UserInfo
if err := json.Unmarshal([]byte(string(input)), &user); err == nil {
fmt.Println(user.Id)
fmt.Println(user.Name)
} else {
fmt.Println(err)
}
}