使用http请求第三方接口的几种方式

本文介绍了使用Hutool和HttpClient库进行第三方接口请求的两种常见方法,包括通过HTTPUtil简化请求和处理文件上传,以及使用HttpClient实现定制化HTTP请求,适合快速开发和灵活控制的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在工作中经常遇到需要请求第三方接口的场景,今天总结一下自己经常使用的方法。

方法一:使用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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值