golang实现各种情况的get请求操作
请求地址
var( requestGetURLNoParamsstring="http://httpbin.org/get" requestGetURLstring="http://httpbin.org/get?a=a&b=b&c=ccc" imageURLstring="http://httpbin.org/image" )
普通get请求
//基本get请求
funcbasicGet(){
resp,err:=http.Get(requestGetURLNoParams)
iferr!=nil{
log.Println("err")
}
deferresp.Body.Close()
b,err:=ioutil.ReadAll(resp.Body)
iferr!=nil{
log.Println("err")
}
fmt.Println(string(b))
}
请求参数放到url.Values{}
//get请求参数放到"net/url"
funcbasicGetURLParams(){
params:=url.Values{}
parseURL,err:=url.Parse(requestGetURLNoParams)
iferr!=nil{
log.Println("err")
}
params.Set("aaa","aaa")
params.Set("age","23")
//如果参数中有中文参数,这个方法会进行URLEncode
parseURL.RawQuery=params.Encode()
urlPathWithParams:=parseURL.String()
resp,err:=http.Get(urlPathWithParams)
iferr!=nil{
log.Println("err")
}
deferresp.Body.Close()
b,err:=ioutil.ReadAll(resp.Body)
iferr!=nil{
log.Println("err")
}
fmt.Println(string(b))
}
自定义请求(添加头、cookie)
//可以设置请求头添加cookie
funcbasicGetHeader(){
client:=http.Client{}
req,err:=http.NewRequest(http.MethodGet,requestGetURLNoParams,nil)
iferr!=nil{
log.Println("err")
}
//添加请求头
req.Header.Add("Content-type","application/json;charset=utf-8")
req.Header.Add("header","header