Golang:发起http请求-GET带参数、POST发送Form和JSON数据
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
)
func main() {
// GET请求带参数
getURL, _ := url.Parse("http://example.com/api")
getQuery := getURL.Query()
getQuery.Add("key1", "value1")
getQuery.Add("key2", "value2")
getURL.RawQuery = getQuery.Encode()
getResponse, err := http.Get(getURL.String())
if err != nil {
panic(err)
}
defer getResponse.Body.Close()
getBody, err := ioutil.ReadAll(getResponse.Body)
if err != nil {
panic(err)
}
fmt.Println("GET Response:", string(getBody))
// POST请求,发送Form数据
postFormURL := "http://example.com/api"
postFormData := url.Values{}
postFormData.Add("key1", "value1")
postFormData.Add("key2", "value2")
postFormBody := bytes.NewBufferString(postFormData.Encode())
postFormResponse, err := http.Post(postFormURL, "application/x-www-form-urlencoded", postFormBody)
if err != nil {
panic(err)
}
defer postFormResponse.Body.Close()
postFormBodyContent, err := ioutil.ReadAll(postFormResponse.Body)
if err != nil {
panic(err)
}
fmt.Println("POST Form Response:", string(postFormBodyContent))
// POST请求,发送JSON数据
postJSONURL := "http://example.com/api"
postJSONData := map[string]string{
"key1": "value1",
"key2": "value2",
}
postJSONBuffer := new(bytes.Buffer)
json.NewEncoder(postJSONBuffer).Encode(postJSONData)
postJSONResponse, err := http.Post(postJSONURL, "application/json", postJSONBuffer)
if err != nil {
panic(err)
}
defer postJSONResponse.Body.Close()
postJSONBodyContent, err := ioutil.ReadAll(postJSONResponse.Body)
if err != nil {
panic(err)
}
fmt.Println("POST JSON Response:", string(postJSONBodyContent))
}
这段代码展示了如何在Go中发起GET请求,带参数;如何发起POST请求,发送application/x-www-form-urlencoded和application/json格式的数据。代码使用了标准库中的http包和url包,并对响应体内容进行了读取和打印。
评论已关闭