【发布时间】:2018-03-05 15:40:24
【问题描述】:
下面是一个表格:
<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--
请注意“Request Payload”,可以看到表单中的两个参数,用户名和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());
现在你明白了,我该如何设置参数的“名称”?
【问题讨论】:
-
您能否分享一个在单击按钮时进行的示例 API 调用。您可以使用浏览器检查部分中的网络设置进行监控。
-
您好,我知道如何监控网络请求,也知道如何使用 HttpClient Httpclient 发送此类请求。让我感到困惑的是如何使用 Java 9 中的 Httpclient 来做到这一点。
-
我的意思是我知道如何使用“Apache”Httpclient发送这样的请求。
-
已更新答案。此处使用的 util 仅用于将文件输入转换为字节数组,也可以是自定义实现。
-
非常感谢您的帮助。
标签: java http multipartform-data http2 java-9