HTTP POST请求发送form-data格式的数据
短信预约 -IT技能 免费直播动态提醒
1、业务需求
发送请求给第三方服务的接口,且请求报文格式为multipart/form-data的数据。支持复杂类型的参数,包含文件类型
2、 依赖包
<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.58</version></dependency><dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.5</version> </dependency>
3、 请求方式实现
public static <T> T doPostFormData(String url, Map<String, Object> param,Class<T> clazz) { return doPostFormData(url, param,new TypeReference<T>() {@Overridepublic Type getType() {return clazz;}}); } public static <T> T doPostFormData(String url, Map<String, Object> param,TypeReference<T> type) { // 创建Http实例 CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建HttpPost实例 HttpPost httpPost = new HttpPost(url); // 请求参数配置 RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000) .setConnectionRequestTimeout(10000).build(); httpPost.setConfig(requestConfig); try { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setCharset(java.nio.charset.Charset.forName("UTF-8")); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); //表单中其他参数 if(param != null) { for(Map.Entry<String, Object> entry: param.entrySet()) { Object value = entry.getValue(); System.err.println(entry.getKey()); if(value instanceof File) { // 文件流 builder.addBinaryBody(entry.getKey(), (File)value); }else { builder.addPart(entry.getKey(),new StringBody(String.valueOf(entry.getValue()), ContentType.create("text/plain", Consts.UTF_8))); } } } HttpEntity entity = builder.build(); httpPost.setEntity(entity); HttpResponse response = httpClient.execute(httpPost);// 执行提交 if (response.getStatusLine().getStatusCode() == HttpStatus.OK.value()) { // 返回 String res = EntityUtils.toString(response.getEntity(), java.nio.charset.Charset.forName("UTF-8")); return JSON.parseObject(res).toJavaObject(type); } } catch (Exception e) { e.printStackTrace(); log.error("调用HttpPost失败!" ,e); } finally { if (httpClient != null) { try { httpClient.close(); } catch (IOException e) { log.error("关闭HttpPost连接失败!",e); } } } return null; }
4、 其他
4.1、 MultipartFile对象转换File对象
4.1.1、 依赖包
commons-io commons-io 2.6
4.1.1、 实现
public static File getFile(String path,MultipartFile multipartFile) {try {File file = new File(path); FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file);return file;} catch (IOException e) {e.printStackTrace();}return null;}
来源地址:https://blog.csdn.net/qq_43432189/article/details/130563323
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341