java发送post请求 formdata,formdata对象上传文件
如何使用爪哇发送表单数据格式的请求上传几部分的文件?供大家参考,具体内容如下
封装了以下工具类:
包com。李耀南。clinkz。常见。util导入Java。io。文件;导入Java。io。io异常;导入Java。nio。字符集。标准字符集;导入Java。util。*;导入Java。util。并发。scheduledexecutorservice导入Java。util。并发。scheduledthreadpoolexecutor导入Java。util。并发。时间单位;导入龙目岛。外部人员。SLF 4j。SLF 4j;导入org。阿帕奇。http。http实体;导入组织。阿帕奇。http。客户。http requestretryhandler导入org。阿帕奇。http。客户。配置。请求配置;导入组织。阿帕奇。http。客户。方法。可关闭的httpresponse导入org。阿帕奇。http。客户。方法。http帖子;导入org。阿帕奇。http。客户。方法。http请求库;导入org。阿帕奇。http。配置。注册表;导入org。阿帕奇。http。配置。注册表生成器;导入组织。阿帕奇。http。连接插座。connectionsocketfactory导入组织。阿帕奇。http。连接插座。plainconnectionsocketfactory导入组织。阿帕奇。http。连接SSL。SSL connectionsocketfactory导入组织。阿帕奇。http。连接SSL。trustselfsignedstrategy导入org。阿帕奇。http。实体。内容类型;导入org。阿帕奇。http。实体。哑剧。http multipartmode导入org。阿帕奇。http。实体。哑剧。multipartentitybuilder导入org。阿帕奇。http。实体。哑剧。内容。文件体;导入组织。阿帕奇。http。impl。客户。可关闭的http客户端;导入组织。阿帕奇。http。impl。客户。defaulthttprequestretryhandler;导入org。阿帕奇。http。impl。客户。http客户端;导入组织。阿帕奇。http。impl。conn . poolinghttpclientconnectionmanager;导入org。阿帕奇。http。SSL。SSL上下文生成器;导入org。阿帕奇。http。util。实体效用;导入org。spring框架。util。收集实用程序;/* * * http utils * * @ author Rot * @ date 2021/10/15 17:45 */@ SLF 4j公开课HttpUtils {/* * *从连接池中获取连接的超时时间-10s */private static int connectionrequesttime out=10000;/** * 客户端和服务器建立连接的超时时间- 握手连接时间-10s */private static int连接超时=60000;/** * 从对方服务接受响应流的时间*/private static int socket超时=60000;/** * 连接池最大连接数*/private static int max total=800;/** * 每个主机的并发*/private static int maxPerRoute=20;私有静态池httpclientconnectionmanager连接管理器=null私有静态CloseableHttpClient httpClient
public static CloseableHttpClient getClient() { return httpClient; } static { log.info("初始化http connection 连接池 ..."); try { // 配置同时支持 HTTP 和 HTPPS SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(builder.build()); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslConnectionSocketFactory).build(); connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); } catch (Exception e) { log.error("初始化http 连接池异常", e); connectionManager = new PoolingHttpClientConnectionManager(); } //连接池统一配置 connectionManager.setMaxTotal(maxTotal); connectionManager.setDefaultMaxPerRoute(maxPerRoute); RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout).setConnectionRequestTimeout(connectionRequestTimeout).setSocketTimeout(socketTimeout).build(); //不做重试功能 HttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler(0, false); httpClient = HttpClients.custom().setConnectionManager(connectionManager).setDefaultRequestConfig(requestConfig).setRetryHandler(retryHandler).build(); ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(1); scheduledExecutorService.scheduleWithFixedDelay(() -> { connectionManager.closeExpiredConnections(); connectionManager.closeIdleConnections(20, TimeUnit.SECONDS); log.info("回收过期的http连接完成 status:{}", connectionManager.getTotalStats()); }, 30, 120, TimeUnit.SECONDS); Runtime.getRuntime().addShutdownHook(new Thread(() -> { log.info("关闭 httpClient 连接"); try { if (httpClient != null) { httpClient.close(); } } catch (IOException e) { log.error("关闭 httpClient 异常", e); } })); } /** * post请求提交form-data上传文件 * * @param url * @param headers 请求头 * @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("multipartFile", new FileBody(file)); // application/octet-stream代表不知道是什么格式的文件 builder.addBinaryBody("media", file, ContentType.create("application/octet-stream"), fileName); HttpEntity entity = builder.build(); httpPost.setEntity(entity); 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 { log.error("对方响应的状态码不在符合的范围内!"); throw new RuntimeException(); } return respContent; } catch (Exception e) { log.error("网络访问异常,请求url地址={},响应体={},error={}", url, response, e); throw new RuntimeException(); } finally { log.info("统一外网请求参数打印,post请求url地址={},响应={},耗时={}毫秒", url, respContent, (System.currentTimeMillis() - startTime)); try { if (response != null) { response.close(); } } catch (IOException e) { log.error("请求链接释放异常", e); } } } /** * 封装请求头 * * @param paramsHeads * @param httpMethod */ private static void packageHeader(Map<String, String> paramsHeads, HttpRequestBase httpMethod) { if (!CollectionUtils.isEmpty(paramsHeads)) { Set<Map.Entry<String, String>> entrySet = paramsHeads.entrySet(); for (Map.Entry<String, String> entry : entrySet) { httpMethod.setHeader(entry.getKey(), entry.getValue()); } } }}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>
核心部分:
// 设置请求头 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("multipartFile", new FileBody(file)); // application/octet-stream代表不知道是什么格式的文件 builder.addBinaryBody("media", file, ContentType.create("application/octet-stream"), fileName); HttpEntity entity = builder.build(); httpPost.setEntity(entity);
注意:这里的builder.addPart("multipartFile", new FileBody(file));,multipartFile对应form表单的字段名称,如果接口更改了字段名称,这里也需要更改
比如我有一个接口是这样定义的:
@PostMapping("/xxx") public void test(@RequestParam(value = "abc") MultipartFile file) { ... }
那么使用上述工具请求该接口的时候,就需要将
builder.addPart("multipartFile", new FileBody(file));
改为
builder.addPart("abc", new FileBody(file));
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持盛行IT。
郑重声明:本文由网友发布,不代表盛行IT的观点,版权归原作者所有,仅为传播更多信息之目的,如有侵权请联系,我们将第一时间修改或删除,多谢。