httpclient发送文件
2021/8/12 23:07:19
本文主要是介绍httpclient发送文件,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
maven坐标
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.5.13</version> </dependency>
代码示例
1 @Test 2 public void test09() throws IOException { 3 String requestUrl = "xxxxx"; 4 CloseableHttpClient httpClient = HttpClients.createDefault(); 5 HttpPost httpPost = new HttpPost(requestUrl); 6 Person person = new Person("强强", "19"); 7 StringBody stringBody = new StringBody(JSONObject.toJSONString(person), ContentType.APPLICATION_JSON); 8 9 MultipartEntityBuilder builder = MultipartEntityBuilder.create(); 10 builder.setCharset(Consts.UTF_8); // 设置编码 11 builder.setContentType(ContentType.create("multipart/form-data", Consts.UTF_8)); // 传递文件 12 builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); // 设置浏览器的模式(否则文件名乱码) 13 14 // 对于普通的表单字段如果含有中文的话,不能通过addTextBody,否则乱码s 15 builder.addBinaryBody("files", 16 new FileInputStream(new File("强强.txt")), 17 ContentType.MULTIPART_FORM_DATA, 18 "强强.txt"); 19 builder.addPart("person", stringBody); 20 HttpEntity build = builder.build(); 21 httpPost.setEntity(build); 22 CloseableHttpResponse response = httpClient.execute(httpPost); 23 HttpEntity entity = response.getEntity(); 24 if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) { 25 System.out.println("请求成功!"); 26 for (Header header : response.getAllHeaders()) { 27 System.out.println(header.getName() + " " + header.getValue()); 28 29 } 30 } 31 // 确保流关闭 32 EntityUtils.consume(entity); 33 response.close(); 34 httpClient.close(); 35 }
这篇关于httpclient发送文件的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-12-29uni-app 中使用 Vant Weapp,怎么安装和配置npm ?-icode9专业技术文章分享
- 2024-12-27Nacos多环境配置学习入门
- 2024-12-27Nacos快速入门学习入门
- 2024-12-27Nacos快速入门学习入门
- 2024-12-27Nacos配置中心学习入门指南
- 2024-12-27Nacos配置中心学习入门
- 2024-12-27Nacos做项目隔离学习入门
- 2024-12-27Nacos做项目隔离学习入门
- 2024-12-27Nacos初识学习入门:轻松掌握服务发现与配置管理
- 2024-12-27Nacos初识学习入门:轻松掌握Nacos基础操作