需要请求第三方接口上传文件,该请求类型是form-data请求
org.apache.httpcomponents httpcore4.4.9 org.apache.httpcomponents httpclient4.5.13 org.apache.httpcomponents httpmime4.5.12
public static void test() { String goodsUrl = "http://0.0.0.0:7000/pangu/"; //本地文件位置 String fileName = "D:\\222.png"; String str = null; try { //添加请求头 HashMapmap = new HashMap<>(); //map.put("token", CommonConstant.token); File file = new File(fileName); str = doPostUploadFile(goodsUrl + "/sacw/CommonConfig/uploadFile", map, file); if(file.exists()) { //boolean delete = file.delete(); } } catch (Exception e) { e.printStackTrace(); } } /** * post请求提交form-data上传文件 * * @param url 上传地址 * @param headers 请求头 * @param file 上传文件 * @return */ public static String doPostUploadFile(String url, Map headers, File file) { HttpPost httpPost = new HttpPost(url); packageHeader(headers, httpPost); String fileName = file.getName(); CloseableHttpResponse response = null; String respContent = null; long startTime = System.currentTimeMillis(); // 设置请求头 boundary边界不可重复,重复会导致提交失败 String boundary = "-------------------------" + UUID.randomUUID().toString(); httpPost.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary); // 创建MultipartEntityBuilder MultipartEntityBuilder builder = MultipartEntityBuilder.create(); // 设置字符编码 builder.setCharset(StandardCharsets.UTF_8); // 模拟浏览器 builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); // 设置边界 builder.setBoundary(boundary); // 设置multipart/form-data流文件 builder.addPart("sendfile", new FileBody(file)); builder.addTextBody("fileType", "1"); // application/octet-stream代表不知道是什么格式的文件 builder.addBinaryBody("media", file, ContentType.create("application/octet-stream"), fileName); HttpEntity entity = builder.build(); httpPost.setEntity(entity); CloseableHttpClient httpClient = HttpClients.createDefault(); try { response = httpClient.execute(httpPost); if (response != null && response.getStatusLine() != null && response.getStatusLine().getStatusCode() < 400) { HttpEntity he = response.getEntity(); if (he != null) { respContent = EntityUtils.toString(he, "UTF-8"); } } else { logger.error("对方响应的状态码不在符合的范围内!"); throw new RuntimeException(); } return respContent; } catch (Exception e) { logger.error("网络访问异常,请求url地址={},响应体={},error={}", url, response, e); throw new RuntimeException(); } finally { logger.info("统一外网请求参数打印,post请求url地址={},响应={},耗时={}毫秒", url, respContent, (System.currentTimeMillis() - startTime)); try { if (response != null) { response.close(); } if(null != httpClient){ httpClient.close(); } } catch (IOException e) { logger.error("请求链接释放异常", e); } } } /** * 封装请求头 * * @param paramsHeads * @param httpMethod */ private static void packageHeader(Map paramsHeads, HttpRequestBase httpMethod) { if (null!= paramsHeads && paramsHeads.size()>0) { Set > entrySet = paramsHeads.entrySet(); for (Map.Entry entry : entrySet) { httpMethod.setHeader(entry.getKey(), entry.getValue()); } } }
注意:这里的builder.addPart("sendfile", new FileBody(file));,multipartFile对应form表单的字段名称。
参考:Java发送form-data请求实现文件上传_IceFloe_Rot的博客-CSDN博客