Java 9 HttpClient 发送多部分/表单数据请求
2022-09-02 02:40:56
以下是表格:
<form action="/example/html5/demo_form.asp" method="post"
enctype=”multipart/form-data”>
<input type="file" name="img" />
<input type="text" name=username" value="foo"/>
<input type="submit" />
</form>
当将提交此表单时,请求将如下所示:
POST /example/html5/demo_form.asp HTTP/1.1
Host: 10.143.47.59:9093
Connection: keep-alive
Content-Length: 326
Accept: application/json, text/javascript, */*; q=0.01
Origin: http://10.143.47.59:9093
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryEDKBhMZFowP9Leno
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4
Request Payload
------WebKitFormBoundaryEDKBhMZFowP9Leno
Content-Disposition: form-data; name="username"
foo
------WebKitFormBoundaryEDKBhMZFowP9Leno
Content-Disposition: form-data; name="img"; filename="out.txt"
Content-Type: text/plain
------WebKitFormBoundaryEDKBhMZFowP9Leno--
请注意“请求有效负载”,您可以在表单中看到两个参数,用户名和img(form-data; name=“img”; filename=“out.txt”),并且finename是文件系统中的真实文件名(或路径),您将在后端(例如spring控制器)中按名称(而不是文件名)接收文件。
如果我们使用Apache Httpclient来模拟请求,我们将编写这样的代码:
MultipartEntity mutiEntity = newMultipartEntity();
File file = new File("/path/to/your/file");
mutiEntity.addPart("username",new StringBody("foo", Charset.forName("utf-8")));
mutiEntity.addPart("img", newFileBody(file)); //img is name, file is path
但是在java 9中,我们可以编写这样的代码:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.
newBuilder(new URI("http:///example/html5/demo_form.asp"))
.method("post",HttpRequest.BodyProcessor.fromString("foo"))
.method("post", HttpRequest.BodyProcessor.fromFile(Paths.get("/path/to/your/file")))
.build();
HttpResponse response = client.send(request, HttpResponse.BodyHandler.asString());
System.out.println(response.body());
现在你明白了,我该如何设置参数的“名称”呢?