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

2. 发送json为参数的post请求

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))
 
}
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. 对返回的结果进行解析

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

猜你喜欢

转载自blog.csdn.net/boss2967/article/details/103874116