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发送文件的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程