阅读 99

httpclient发送文件

maven坐标

<dependency>
      <groupId>org.apache.httpcomponentsgroupId>
      <artifactId>httpclientartifactId>
       <version>4.5.13version>
dependency>
<dependency>
     <groupId>org.apache.httpcomponentsgroupId>
     <artifactId>httpmimeartifactId>
     <version>4.5.13version>
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     }

 

原文:https://www.cnblogs.com/ncyj/p/15135123.html

文章分类
代码人生
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐