Http请求
最近在项目中模拟http请求比较多,总结了一下go语言中的各种http请求
package main
import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
// 发送简单的GET请求
func SendSimpleGetRequest() {
resp, err := http.Get("https://baidu.com")
if err != nil {
panic(err)
}
defer resp.Body.Close()
s, err := ioutil.ReadAll(resp.Body)
fmt.Printf(string(s))
}
// 发送复杂的Get请求
func SendComplexGetRequest() {
params := url.Values{}
Url, err := url.Parse("http://baidu.com?fd=fdsf")
if err != nil {
panic(err.Error())
}
params.Set("a", "fdfds")
params.Set("id", string("1"))
//如果参数中有中文参数,这个方法会进行URLEncode
Url.RawQuery = params.Encode()
urlPath := Url.String()
resp, err := http.Get(urlPath)
defer resp.Body.Close()
s, err := ioutil.ReadAll(resp.Body)
fmt.Println(string(s))
}
// 使用PostForm进行请求
func httpPostForm() {
// params:=url.Values{}
// params.Set("hello","fdsfs") //这两种都可以
params := url.Values{"key": {"Value"}, "id": {"123"}}
resp, _ := http.PostForm("http://baidu.com", params)
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
}
// 通用的http请求
func httpDo() {
client := &http.Client{}
urlmap := url.Values{}
urlmap.Add("client_id", "esss")
urlmap.Add("client_secret", "sk")
parms := ioutil.NopCloser(strings.NewReader(urlmap.Encode())) //把form数据编下码
req, err := http.NewRequest("POST", "www.baidu.com", parms)
if err != nil {
// handle error
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Cookie", "name=anny")
resp, err := client.Do(req)
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}
fmt.Println(string(body))
}
func main() {
httpDo()
}