java项目调用第三方接口的三种方式

您所在的位置:网站首页 第三方接口怎么调用 java项目调用第三方接口的三种方式

java项目调用第三方接口的三种方式

2024-07-11 02:43:32| 来源: 网络整理| 查看: 265

问题情境:

        在工作中经常出现调用第三方接口的方式,这次需求中有需要调用阿里云的接口上传文件,顺便对调用方式都做了下整理,方便后续查看。

一.Hutool-http方式(详情参考:https://www.hutool.cn/) 1.1 pom中添加hutool的依赖       cn.hutool hutool-all 4.1.0

     

                  com.alibaba         fastjson         1.2.4       

 

1.2 代码示例,   1.2.1上传文件第一种就是map的值是转成InputStreamResource,如下两种列举 1 import cn.hutool.core.io.resource.InputStreamResource; 2 3 @RequestMapping("/fileupload") 4 public String upload(MultipartFile file) { 5 String result = ""; 6 try { 7 InputStreamResource isr = new InputStreamResource(file.getInputStream(), 8 file.getOriginalFilename()); 9 10 Map params = new HashMap(); 11 params.put("file", isr); 12 params.put("path", "86501729"); 13 params.put("output", "json"); 14 String resp = HttpUtil.post(url, params); 15 Console.log("resp: {}", resp); 16 result = resp; 17 } catch (IOException e) { 18 e.printStackTrace(); 19 } 20 21 return result; 22 }

1 /** 2 * 3 * @param url 阿里云文件上传接口 4 * @param img 添加水印后的图片 5 * @param newname 新图片名称 6 * @return 7 */ 8 public String fileHutool(String url,BufferedImage img,String newname) { 9 try { 10 Map param =new HashMap(); 11 //1.图片压缩且转成byte[]数组 12 byte[] bytes=bufferedImageTobytes(img, 1); 13 //2.数组转输入流 14 InputStream buffin = new ByteArrayInputStream(bytes); 15 //3.输入流转MultipartFile对象, 16 MultipartFile file = new MockMultipartFile(ContentType.APPLICATION_OCTET_STREAM.toString(), buffin); 17 18 //4.把MultipartFile这个对象转成输入流资源(InputStreamResource) 19 InputStreamResource isr = new InputStreamResource(file.getInputStream(), 20 file.getOriginalFilename()); 21 /*5.把条件组成map传给hutool,已测过的hutool文件上传 22 * 第一种是map的值是一个File, 23 * 第二种就是map的值是转成InputStreamResource 24 */ 25 param.put("myfile",isr); 26 param.put("token", "1_grand"); 27 param.put("name",newname); 28 /** 29 * 接口会返回一个json格式的数据 30 * {"code":0,"msg":"success","data":{"url":"http://grandpic.oss-cn-shanghai.aliyuncs.com/pics/isr.jpg"}} 31 */ 32 String post=HttpUtil.post(url,param); 33 JSONObject josn=JSON.parseObject(post); 34 //获取data下的接口返回路径 35 JSONObject jurl=JSON.parseObject(josn.get("data").toString()); 36 37 return jurl.get("url").toString().length()>0?jurl.get("url").toString():null; 38 } catch (IOException e) { 39 e.printStackTrace(); 40 return null; 41 } 42 43 }

 

1.2.2 上传传文件第二种是map的值是一个File类型,一下两种列 1 @RequestMapping("/order") 2 public String getgeneOrder1(@Value("${system.fileUpload}")String url) throws IOException { 3 Map param =new HashMap(); 4 File file=new File("D:\\文件表\\test2.jpg"); 5 param.put("myfile",file); 6 param.put("token", "1_grand"); 7 param.put("name", "isr.jpg"); 8 String post=HttpUtil.post(url,param); 9 JSONObject josn=JSON.parseObject(post); 10 JSONObject jurl=JSON.parseObject(josn.get("data").toString()); 11 System.out.println(jurl.get("url")); 12 return post; 13 }

 

 二.HttpClient方式 2.1 pom中添加httpclient依赖 org.apache.httpcomponents httpclient 4.5.3 org.apache.httpcomponents httpmime 4.5.3 2.2 代码案列 1 @PostMapping("/order") 2 public String getgeneOrder(@Value("${system.fileUpload}")String url) throws IOException { 3 //1:创建一个httpclient对象 4 HttpClient httpclient = new DefaultHttpClient(); 5 Charset charset = Charset.forName("UTF-8");//设置编码 6 7 //2:创建http的发送方式对象,是GET还是post 8 HttpPost httppost = new HttpPost(url); 9 10 //3:创建要发送的实体,就是key-value的这种结构,借助于这个类,可以实现文件和参数同时上传 11 MultipartEntity reqEntity = new MultipartEntity(); 12 File myfile=new File("D:\\文件表\\test3.jpg"); 13 FileBody fileContent = new FileBody(myfile); 14 15 reqEntity.addPart("myfile",fileContent); 16 StringBody content = new StringBody("test.jpg",charset); 17 reqEntity.addPart("name",content); 18 StringBody contenttoken = new StringBody("1_grand",charset); 19 reqEntity.addPart("token",contenttoken); 20 21 httppost.setEntity(reqEntity); 22 //4:执行httppost对象,从而获得信息 23 HttpResponse response = httpclient.execute(httppost); 24 HttpEntity resEntity = response.getEntity(); 25 26 String resString = EntityUtils.toString(resEntity); 27 return resString; 28 }

  这一部分参考这个地址:https://segmentfault.com/a/1190000020158062

@RequestMapping("/upload1") public String upload1(MultipartFile file) { String result = ""; try { CloseableHttpClient httpClient = HttpClientBuilder.create().build(); CloseableHttpResponse httpResponse = null; RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(200000) .setSocketTimeout(2000000) .build(); HttpPost httpPost = new HttpPost(UPLOAD_PATH); httpPost.setConfig(requestConfig); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create() .setMode(HttpMultipartMode.BROWSER_COMPATIBLE) .setCharset(Charset.forName("UTF-8")) .addTextBody("output", "json") .addBinaryBody("file", file.getInputStream(), ContentType.DEFAULT_BINARY, file.getOriginalFilename()); httpPost.setEntity(multipartEntityBuilder.build()); httpResponse = httpClient.execute(httpPost); if (httpResponse.getStatusLine().getStatusCode() == 200) { String respStr = EntityUtils.toString(httpResponse.getEntity()); System.out.println(respStr); result = respStr; } httpClient.close(); httpResponse.close(); } catch (Exception e) { e.printStackTrace(); } return result; } 三.OkHttp3方式 3.1 OkHttp3引入pom依赖       com.squareup.okhttp3 okhttp 3.9.1 3.2.参考案列 1 @RequestMapping("/fileorder") 2 public String upload2(MultipartFile file) { 3 String result = ""; 4 try { 5 OkHttpClient httpClient = new OkHttpClient(); 6 MultipartBody multipartBody = new MultipartBody.Builder(). 7 setType(MultipartBody.FORM) 8 .addFormDataPart("file", file.getOriginalFilename(), 9 RequestBody.create(MediaType.parse("multipart/form-data;"), 10 file.getBytes())) 11 .addFormDataPart("output", "json") 12 .build(); 13 14 Request request = new Request.Builder() 15 .url(UPLOAD_PATH) 16 .post(multipartBody) 17 .build(); 18 19 Response response = httpClient.newCall(request).execute(); 20 if (response.isSuccessful()) { 21 ResponseBody body = response.body(); 22 if (body != null) { 23 result = body.string(); 24 System.out.println(result); 25 } 26 } 27 } catch (Exception e) { 28 e.printStackTrace(); 29 } 30 31 return result; 32 }

 

总结:

个人觉得Hutool的是最简单的,最方便的,Hutool是gethub上的一个开源项目,还有很多其他的工具,个人觉得还可以,参考文档地址:https://www.hutool.cn/

个人觉得hutool的Http已经够用了,底层是基于jdk的HttpUrlConnection实现的。

如果对性能有特殊要求的,可以考虑httpclient或者OKHttp,后两者相对而言,更推荐使用OkHttp。

排名结果就是:hutool



【本文地址】

公司简介

联系我们

今日新闻


点击排行

实验室常用的仪器、试剂和
说到实验室常用到的东西,主要就分为仪器、试剂和耗
不用再找了,全球10大实验
01、赛默飞世尔科技(热电)Thermo Fisher Scientif
三代水柜的量产巅峰T-72坦
作者:寞寒最近,西边闹腾挺大,本来小寞以为忙完这
通风柜跟实验室通风系统有
说到通风柜跟实验室通风,不少人都纠结二者到底是不
集消毒杀菌、烘干收纳为一
厨房是家里细菌较多的地方,潮湿的环境、没有完全密
实验室设备之全钢实验台如
全钢实验台是实验室家具中较为重要的家具之一,很多

推荐新闻


图片新闻

实验室药品柜的特性有哪些
实验室药品柜是实验室家具的重要组成部分之一,主要
小学科学实验中有哪些教学
计算机 计算器 一般 打孔器 打气筒 仪器车 显微镜
实验室各种仪器原理动图讲
1.紫外分光光谱UV分析原理:吸收紫外光能量,引起分
高中化学常见仪器及实验装
1、可加热仪器:2、计量仪器:(1)仪器A的名称:量
微生物操作主要设备和器具
今天盘点一下微生物操作主要设备和器具,别嫌我啰嗦
浅谈通风柜使用基本常识
 众所周知,通风柜功能中最主要的就是排气功能。在

专题文章

    CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭