首页 > 文章列表 > golang使用 http.NewRequest(...)发出 URL 编码的 POST 请求?

golang使用 http.NewRequest(...)发出 URL 编码的 POST 请求?

golang
112 2023-06-27

问题内容

golang使用 http.NewRequest(...)发出 URL 编码的 POST 请求?

正确答案

可以像下面这样:

package main

import (
	"net/http"
	"net/url"
	"strings"
)

func main() {
	form := url.Values{}
	form.Add("key1", "value1")
	form.Add("key2", "value2")

	url := "http://example.com/post"
	req, err := http.NewRequest("POST", url, strings.NewReader(form.Encode()))
	if err != nil {
		// 处理错误
	}

	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		// 处理错误
	}
	defer resp.Body.Close()

	// 处理响应
	// ...
}