原创文章,转载请注明出处
https://qiedd.com/
今天来学习一下使用 Golang 发起 POST 请求
示例代码
package main import ( "fmt" "io" "net/http" "net/url" "strings" "time" ) func main() { u := url.Values{} // 请求参数 u.Add("message", "text") // 创建一个客户端 client := &http.Client{ Timeout: 10 * time.Second, } // 创建一个请求 req, err := http.NewRequest("POST", "https://httpbin.org/post", strings.NewReader(u.Encode())) if err != nil { fmt.Println(err) } // 添加 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/x-www-form-urlencoded") // 执行请求 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": {}, "data": "", "files": {}, "form": { "message": "text" }, "headers": { "Accept-Encoding": "gzip", "Content-Length": "12", "Content-Type": "application/x-www-form-urlencoded", "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-62f0a344-41b83f7062e96f2d24eff7df" }, "json": null, "origin": "", "url": "https://httpbin.org/post" }
0 条评论