- 遇到的坑:
- 查询了网上的博客,百分之99的人在添加字节流文件的时候都是这么写:
MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addBinaryBody("file", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流 builder.addTextBody("filename", fileName);// 类似浏览器表单提交,对应input的name和value HttpEntity entity = builder.build(); httpPost.setEntity(entity);
- 我在发送的时候总是报错,最后看了下addTextBody的其他方法,我们可以直接把字节数组传进去,试了一下成功了
MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setCharset(StandardCharsets.UTF_8); // 文件流 builder.addBinaryBody("filename",file.getBytes()); HttpEntity entity = builder.build(); httpPost.setEntity(entity);
- 查询了网上的博客,百分之99的人在添加字节流文件的时候都是这么写:
- 使用具体步骤:
- 1.需要导入的pox.xml:
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.4</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.4</version> </dependency>
- 具体代码:
public static String httpClientUploadFile(String url, MultipartFile file, Map<String, String> header) { CloseableHttpClient httpClient = HttpClients.createDefault(); String result = ""; try { HttpPost httpPost = new HttpPost(url); //请求头 if (MapUtils.isNotEmpty(header)) { for (Map.Entry<String, String> entry : header.entrySet()) { httpPost.addHeader(entry.getKey(), entry.getValue()); } } MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setCharset(StandardCharsets.UTF_8); // 文件流 builder.addBinaryBody("filename",file.getBytes()); HttpEntity entity = builder.build(); httpPost.setEntity(entity); // 执行提交 HttpResponse response = httpClient.execute(httpPost); HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { // 将响应内容转换为字符串 result = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8); } } catch (Exception e) { log.error(e.getMessage()); } finally { try { httpClient.close(); } catch (IOException e) { log.error(e.getMessage()); } } return result; }
- 1.需要导入的pox.xml: