go http包
01 普通的(不指定header的)
- get
返回结果是json
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
func main() {
response, err := http.Get("")
if err != nil {
return
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body) // 假如返回的是json数据
if err != nil {
return
}
type result struct {
}
type responseResult struct {
Result []result `json:"result"`
}
var responseData responseResult
json.Unmarshal(body, &responseData) // json转化为struct,这里必须是指针
fmt.Println(responseData) // struct
}
- post
传的指,和返回结果都是json
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
func main() {
type requestData struct {
userName string
}
var request requestData
request.userName = "lynn"
jsonData, _ := json.Marshal(request) // 把struct对象转化为json对象
response, err := http.Post("", "application/json;charset=utf-8", bytes.NewReader(jsonData)) // bytes.NewReader把json对象装华为二进制
if err != nil {
return
}
defer response.Body.Close() // 必须关闭
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return
}
type result struct {
}
type responseResult struct {
Result []result `json:"result"`
}
var responseData responseResult
json.Unmarshal(body, &responseData) // 这里必须是指针
fmt.Println(responseData)
}
总结:
1 只能是get和post
2 一般不用这种方法,因为都会检查token
02 指定header
- get、post、put、delete
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
func main() {
type requestData struct {
userName string
}
var request requestData
request.userName = "lynn"
jsonData, _ := json.Marshal(request) // 转化为json字符串
response, err := http.NewRequest("POST", "url", bytes.NewReader(jsonData)) // 方法必须大写
if err != nil {
return
}
response.Header.Set("Content-Type", "application/json") // 设置header
response.Header.Set("X-Auth-Token", "token")
defer response.Body.Close()
client := http.Client{} // 创建连接
r1, _ := client.Do(response) // 发起请求
b1, errs := ioutil.ReadAll(r1.Body) // 得到返回值。这里是json
if errs != nil {
return
}
type result struct {
}
type responseResult struct {
Result []result `json:"result"` // 字段首字母必须大写
}
var responseData responseResult
json.Unmarshal(b1, &responseData) // 必须是指针
fmt.Println(responseData)
}
总结:
- httpObj, err := http.NewRequest("请求方法", "url", bytes.NewReader(""))
仅仅是创建一个请求对象
第一个参数是请求方法:大写POST、GET、PUT、DELETE等。也可以http.MethodDelete等
第二个参数是url
第三个参数是要传的参数
- defer httpObj.Body.Close() // 注意必须是连接对象关闭
- httpObj.Header.Set("key", "value") // 设置header,可以设置多对key,value
- client := http.Client{} // 真正创建http连接
- responseBody, err := client.Do(httpObj) // 真正发起请求
- responseJson, errs := ioutil.ReadAll(responseBody.Body) // 从body体中获取返回值