闽公网安备 35020302035485号
POST http://httpbin.org/post HTTP/1.1 Content-Type: application/x-www-form-urlencoded username=poloxue&password=123456Content-Type 是 application/x-www-form-urlencoded,数据通过 urlencoded 方式组织。
<form method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit">
</form>
通过 Post 提交 form 表单,Content-Type 默认是 application/x-www-form-urlencoded。data := make(url.Values)
data.Set("username", "poloxue")
data.Set("password", "123456")
// 按 urlencoded 组织数据
body, _ := data.Encode()
// 堆代码 duidaima.com
// 创建请求并设置内容类型
request, _ := http.NewRequest(
http.MethodPost,
"http://httpbin.org/post",
bytes.NewReader(body),
)
request.Header.Set(
"content-type",
"application/x-www-form-urlencoded",
)
http.DefaultClient.Do(request)
回想下前面说的三个步骤,组织请求体数据、设置 Content-Type 和发送请求。http.Post(
"http://httpbin.org/post",
"application/x-www-form-urlencoded",
bytes.NewReader(body),
)
上传文件 RFC 1867
文件上传的需求很常见,但默认的 form 表单提交方式并不支持。如果是单文件上传,通过 body 二进制流就可以实现。但如果是一些更复杂的场景,如上传多文件,则需要自定义上传协议,而且客户端和服务端都要提供相应的支持。<form
action="http://httpbin.org/post"
method="post"
enctype="multipart/form-data"
>
<input type="text" name="words"/>
<input type="file" name="uploadfile1">
<input type="file" name="uploadfile2">
<input type="submit">
</form>
提交表单后,将会看到请求的内容大致形式,如下:POST http://httpbin.org/post HTTP/1.1 Content-Type: multipart/form-data; boundary=285fa365bd76e6378f91f09f4eae20877246bbba4d31370d3c87b752d350 multipart/form-data; boundary=285fa365bd76e6378f91f09f4eae20877246bbba4d31370d3c87b752d350 --285fa365bd76e6378f91f09f4eae20877246bbba4d31370d3c87b752d350 Content-Disposition: form-data; name="uploadFile1"; filename="uploadfile1.txt" Content-Type: application/octet-stream upload file1 --285fa365bd76e6378f91f09f4eae20877246bbba4d31370d3c87b752d350 Content-Disposition: form-data; name="uploadFile1"; filename="uploadfile2.txt" Content-Type: application/octet-stream upload file2 --285fa365bd76e6378f91f09f4eae20877246bbba4d31370d3c87b752d350 Content-Disposition: form-data; name="words" 123 --285fa365bd76e6378f91f09f4eae20877246bbba4d31370d3c87b752d350--注:如果使用 chrome 浏览器的开发者工具,为了性能考虑,无法看到看到这部分内容。而且,如果提交的是二进制流,只是一串乱码,也没什么可看的。
bodyBuf := &bytes.Buffer{}
writer := multipart.NewWriter(payloadBuf)
先组织文件内容,两个文件的组织逻辑相同,就以 uploadfile1 为例进行介绍。在 writer 之上创建一个 fileWriter,用于写入文件 uploadFile1 的内容,fileWriter, err := writer.CreateFormFile("uploadFile1", filename)
打开要上传的文件,uploadfile1,将文件内容拷贝到 fileWriter中,如下:f, err := os.Open("uploadfile1")
...
io.Copy(fileWriter, f)
添加字段就非常简单了,假设设置 words 为 123,代码如下:writer.WriteField("words", "123")
完成所有内容设置后,一定要记得关闭 Writer,否则,请求体会缺少结束边界。writer.Close()完成了数据的组织。
r, err := http.Post(
"http://httpbin.org/post",
writer.FormDataContentType(),
body,
)
完成了支持文件上传的表单提交。