在工作中经常遇到需要请求第三方接口的场景,今天总结一下自己经常使用的方法。
方法一:使用cn.hutool包封装好的方法,比较简单直接用即可。
1.pom中加入依赖。
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.0.7</version>
</dependency>
调用
//参数 请求地址 参数只能是String类型 如果需要传byte[] 或者文件参照下面的方法
public void hutoolHttpMethod(String url){
String result=HttpUtil.post(url,"");
String result=HttpUtil.get(url);
}
如果需要传byte[] 或者文件
public void hutoolHttpMethod(String url){
Map map=new HashMap();
File file=new File("D:\\home\data\a.txt");
map.put("file",file);//参数是文件类型
map.put("str","data");//参数是String 类型
//都可以封装近map里面一起发送 这种方法有点类似表单提交后台的方式
HttpResponse response=HttpRequest.post(url).form(map).execute();
String body=response.body();//返回的信息都存在response
JSONObject jsonObject=JSONObject.parseObject(body);
//第三方接口返回的是一个布尔 所以取到对应的key转换为对应的类型
Boolean datas=JSON.parseObject(JSON.toJSONString(jsonObject.get("data")),Boolean.class);
if(!datas){
logger.info("接口请求失败");
}
}
接收方接口
public ReturnObject<Boolean> commit(HttpServletRequest request,HttpServletResponse response,
@RequestParam MultipartFile[] files){
//获取报文参数
String data=request.getParameter("str");
//获取文件类型的参数
MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
Map<String,MultipartFile> map=multiRequest.getFileMap();
return new ReturnObject<Boolean>.ReturnSucObject(true);
}
以上是hutool提供的几种方式,下面说一下如果用httpclient如何请求第三方接口
public void httpClientMetthod(String url){
CloseableHttpClient httpClient=HttpClient.createDefault();
HttpPost post =new HttpPost(url);
String strData="xxxx";
StringEntity stringEntity=new StringEntity(strData,"UTF-8");
stringEntity.setContentType("application/json");
post.setEntity(stringEntity);
CloseableHttpResponse response=HttpClient.execute(post);
HttpEntity entity=response.getEntity();
/*
如果返回是json类型的报文
可以使用String str=EntityUtils.toString(entity);
然后转为jsonObject 获取对应的报文key即可
*/
/*
如果用作文件下载返回是个文件流
那就需要把返回来的内容转为流
InputStream content=entity.getContent();
byte[] bytes=inputByte(content);
*/
response.close();
httpClient.close();
}
//InputStream 转为byte[]
public static final byte[] inputByte(InputStream inputStream){
ByteArrayOutputStream swapStream=new ByteArrayOutputStream();
byte[] buff=new byte[1024];
int rc=0;
while((rc=inputStream.read(buff))!=-1){
swapStream.write(buff,0,rc);
}
byte[] bytes=swapStream.toByteArray();
swapStream.close();
return bytes;
}
如果参数中还是有file类型怎么办?如下方法解决
public void httpClientMetthod(String url){
CloseableHttpClient httpClient=HttpClient.createDefault();
HttpPost post =new HttpPost(url);
MultipartEntityBuilder builder=MultipartEntityBuilder.create();
builder.setCharset(Charset.forName("utf-8"));
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
File file=new File("D:\\a.txt");
InputStream inputStream=file.getInputStream();
builder.addBinaryBody("upload",inputStream,ContentType.MULTIPART_FORM_DATA,fileName);
builder.addTextBody("filepath","test"+System.currentTimeMillis());
builder.addTextBody("groupname","group1");
HttpEntity entity=builder.build();
post.setEntity(entity);
CloseableHttpResponse response=HttpClient.execute(post);
HttpEntity entity=response.getEntity();
response.close();
httpClient.close();
}
httpclient 需要的依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.5</version>
</dependency>