- 基础概念
- 请求:客户端访问服务端
- 响应:服务端对客户端的应答
- 示例图
- 带有特殊请求头和cookie值得客户端请求方式
- 使用:http.NewRequest,Do()组合。并且在创建请求的时候,带上cookie值和其他请求头
- 参考代码
package main import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" "time" ) var cookies []*http.Cookie var url = "XXXXX" // login func Login() { req := ReqProto{} data := make(map[string]string) data["test"] = "11" req.Data = data logginClient := http.Client{} logginJsonStr, err := json.Marshal(&req) if err != nil { err := fmt.Errorf("登录发起post请求时,json.Mashal错误:%v", err) fmt.Println(err) return } logginRequest, err := http.NewRequest("POST", url, bytes.NewBuffer(logginJsonStr)) if err != nil { err := fmt.Errorf("登录发起post请求时,http.NewRequest错误:%v", err) fmt.Println(err) return } logginRequest.Header.Set("Content-Type", "application/json") logginRequest.Header.Set("Content-Type", "application/x-www-form-urlencoded") loginResponse, err := logginClient.Do(logginRequest) if err != nil { err := fmt.Errorf("登录发起post请求时,client.Do错误:%v", err) fmt.Println(err) return } fmt.Println(loginResponse) if loginResponse.StatusCode != 200 { err := fmt.Errorf("登录发起post请求时,response.StatusCode:%v", loginResponse.StatusCode) fmt.Println(err) return } else { data, err := ioutil.ReadAll(loginResponse.Body) if err != nil { fmt.Println(err) return } var dataJSON interface{} json.Unmarshal(data, &dataJSON) fmt.Println(dataJSON) } fmt.Println("登录成功") cookies = loginResponse.Cookies() } // StaticData func StaticData() { client := http.Client{} req, err := http.NewRequest("GET",url, nil) if err != nil { fmt.Println(err) return } for i := 0; i < len(cookies); i++ { req.AddCookie(cookies[i]) } resp, err := client.Do(req) if err != nil { fmt.Println(err) return } defer resp.Body.Close() data, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println(err) return } fmt.Println(string(data)) } func main() { Login() StaticData() }
原文地址:https://www.cnblogs.com/MyUniverse/p/11704639.html
时间: 2024-10-09 05:52:10