
如何使用 httpclient 发送带文件和参数的 http 请求?
问题描述:
用户希望通过 java 程序发送一个包含文件和参数的 http 请求,但尝试使用 hutool 框架时遇到困难。
解决方案:
hutool 的 httprequest 确实无法为 multipartformdata 的每一项单独设置 content-type 和其他属性标头。因此,建议使用 httpclient 框架来发送此类 http 请求:
导入依赖
立即学习“Java免费学习笔记(深入)”;
<dependency>
<groupid>org.apache.httpcomponents</groupid>
<artifactid>httpclient</artifactid>
<version>4.5.13</version>
</dependency>创建 httprequest
httppost request = new httppost("http://example.com/upload");构造请求体
multipartentitybuilder multipartentitybuilder = multipartentitybuilder.create();
multipartentitybuilder.addpart("file", new filebody(new file("path/to/file.txt")));
multipartentitybuilder.addpart("参数名1", new stringbody("参数值1"));
multipartentitybuilder.addpart("参数名2", new stringbody("参数值2"));
httpentity multiparthttpentity = multipartentitybuilder.build();
request.setentity(multiparthttpentity);设置请求头
request.setheader(httpheaders.content_type, multiparthttpentity.getcontenttype().getvalue());
执行请求
CloseableHttpResponse response = HttpClientBuilder.create().build().execute(request);
通过使用 httpclient,可以轻松构造 multipartformdata 请求体并设置必要的请求头,从而发送带有文件和参数的 http 请求。
以上就是Java中如何用HttpClient发送包含文件和参数的HTTP请求?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号