前言
对接某公司的接口,涉及到资质上传等业务。需要对接他们的上传附件接口。
JDK1.8 httpclient 4.x
封装httpclient方法
public static String postFileMultiPart(String url,Map reqParam) throws IOException{CloseableHttpClient httpclient = HttpClients.createDefault();try {// 创建httpHttpPost httppost = new HttpPost(url);//setConnectTimeout:设置连接超时时间,单位毫秒。setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒。RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(15000).build();httppost.setConfig(defaultRequestConfig);MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();for(Map.Entry param : reqParam.entrySet()){multipartEntityBuilder.addPart(param.getKey(), param.getValue());}HttpEntity reqEntity = multipartEntityBuilder.build();httppost.setEntity(reqEntity);// 执行post请求.CloseableHttpResponse response = httpclient.execute(httppost);System.out.println("got response");try {// 获取响应实体HttpEntity entity = response.getEntity();if (entity != null) {return EntityUtils.toString(entity, Charset.forName("UTF-8"));}} finally {response.close();}} finally {// 关闭连接,释放资源try {httpclient.close();} catch (IOException e) {e.printStackTrace();}}return null;}
因为我方系统需要给前端提供上传接口 使用的MultipartFile
来接收文件
所以这边需要MultipartFile转下File文件
public static File transferToFile(MultipartFile multipartFile) {//选择用缓冲区来实现这个转换即使用java 创建的临时文件 使用 MultipartFile.transferto()方法 。File file = null;try {String originalFilename = multipartFile.getOriginalFilename();//获取文件后缀String prefix = originalFilename.substring(originalFilename.lastIndexOf("."));file = File.createTempFile(originalFilename, prefix);multipartFile.transferTo(file);//删除临时文件file.deleteOnExit();} catch (IOException e) {e.printStackTrace();}return file;}
方法调用
public RestResponse attachment(MultipartFile file) throws Exception {Map reqParam = new HashMap();//普通类型reqParam.put("appId", new StringBody("appid", ContentType.MULTIPART_FORM_DATA));//文件reqParam.put("file", new FileBody(FileUploadUtils.transferToFile(file), ContentType.IMAGE_JPEG));String result = HttpClientUtil.postFileMultiPart("http://www.com/attachment", reqParam);}
后记
一顿操作对接完事。肯定有朋友问 为什么不让前端兄弟直接对接呢。因为对接的接口有权限校验。前端直接调会有泄漏token和秘钥的风险。