java发送form-data请求实现文件上传的示例代码
作者:凌抆莂
最近做一个需求,需要请求第三方接口上传文件,该请求类型是form-data请求,本文就来介绍一下java发送form-data请求实现文件上传的示例代码,感兴趣的可以了解一下
一、业务需求:
需要请求第三方接口上传文件,该请求类型是form-data请求
二、postmant请求结果如下
三、maven依赖:
<!--http--> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>4.4.9</version> </dependency> <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.12</version> </dependency>
四、java实现请求
public static void test() { String goodsUrl = "http://0.0.0.0:7000/pangu/"; //本地文件位置 String fileName = "D:\\222.png"; String str = null; try { //添加请求头 HashMap<String, String> map = 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<String, String> 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<String, String> paramsHeads, HttpRequestBase httpMethod) { if (null!= paramsHeads && paramsHeads.size()>0) { Set<Map.Entry<String, String>> entrySet = paramsHeads.entrySet(); for (Map.Entry<String, String> entry : entrySet) { httpMethod.setHeader(entry.getKey(), entry.getValue()); } } }
注意:这里的builder.addPart("sendfile", new FileBody(file));
,multipartFile
对应form表单的字段名称。
参考:Java发送form-data请求实现文件上传_IceFloe_Rot的博客-CSDN博客
到此这篇关于java发送form-data请求实现文件上传的示例代码的文章就介绍到这了,更多相关java发送form-data请求上传内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!