原创文章,转载请注明出处
https://qiedd.com/
示例代码
package main import ( "fmt" "io" "net/http" "net/url" "time" ) func main() { u := url.Values{} // 请求参数 u.Add("message", "text") // 创建一个客户端 client := &http.Client{ Timeout: 10 * time.Second, } // 创建一个请求 req, err := http.NewRequest("GET", "https://httpbin.org/get", nil) if err != nil { fmt.Println(err) } // 格式化参数 req.URL.RawQuery = u.Encode() // 添加 Headers req.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36") req.Header.Add("content-type", "application/json") // 执行请求 resp, err := client.Do(req) if err != nil { fmt.Println(err) } // 读取响应 body, err := io.ReadAll(resp.Body) if err != nil { fmt.Println(err) } // 延迟关闭 defer resp.Body.Close() // 输出响应 fmt.Println(string(body)) }
响应示例
{ "args": { "message": "text" }, "headers": { "Accept-Encoding": "gzip", "Content-Type": "application/json", "Host": "httpbin.org", "User-Agent": "Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36", "X-Amzn-Trace-Id": "Root=1-62f0b5c6-0e53e1343e3a815d23fd6c3c" }, "origin": "", "url": "https://httpbin.org/get?message=text" }
0 条评论