httpClient配置使用

使用原因:为了建立2个项目的通讯
一、配置(2个项目都需要添加):

       <!-- httpclient的接口  -->
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.5.5</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpcore</artifactId>
			<version>4.4</version>
		</dependency>

二、通用接口实现
1、post 有参通用

//httpClient请求外部接口
public CommonResponse httpClientConn(String url,String parm);
//httpClient请求外部接口 post 有参 通用
@Override
public CommonResponse httpClientConn(String url,String parm) {
	if(EmptyUtil.isEmpty(url)){
		return new CommonResponse(false, "请求路径为空");
	}
	if(EmptyUtil.isEmpty(parm)){
		return new CommonResponse(false, "请求参数为空");
	}
	logger.info("httpPost请求开始,参数为  url:" +url+",parm:"+parm);
	CloseableHttpClient httpClient = HttpClientBuilder.create().build();
	HttpPost httpPost = new HttpPost(url);
	StringEntity entity = new StringEntity(parm, "UTF-8");
	entity.setContentType("application/json;charset=utf-8");
	//post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
	httpPost.setEntity(entity);
	httpPost.setHeader("Content-Type", "application/json;charset=utf8");
	// 响应模型
	CloseableHttpResponse response = null;
	try{
		// 由客户端执行(发送)Post请求
		response= httpClient.execute(httpPost);
		// 从响应模型中获取响应实体
		HttpEntity responseEntity= response.getEntity();
		logger.info("httpPost请求响应状态为:"+ response.getStatusLine());
		if(responseEntity!= null) {
			logger.info("httpPost请求响应内容长度为:"+ responseEntity.getContentLength());
			String str = EntityUtils.toString(responseEntity, "UTF-8");
			CommonResponse commonResponse = JSON.parseObject(str,CommonResponse.class);
			logger.info("httpPost请求响应内容为:"+ str);
			return new CommonResponse(true,"发送成功","",commonResponse.getData());
		}
	} catch(ClientProtocolException e) {
		logger.error("httpPost请求ClientProtocolException:",e);
	} catch(ParseException e) {
		logger.error("httpPost请求ParseException:",e);
	} catch(IOException e) {
		logger.error("httpPost请求IOException:",e);
	} finally{
		try{
			// 释放资源
			if(httpClient!= null) {
			httpClient.close();
			}
			if(response!= null) {
			response.close();
			}
		} catch(IOException e) {
			e.printStackTrace();
		}
	}
	return new CommonResponse(false, "httpPost请求响应失败");
}

2 get请求 有参

public String httpClientGet(String url, Map<String,String> map);
@Override
public String httpClientGet(String url, Map<String, String> map) {
	String result = null;
	CloseableHttpClient httpClient = HttpClients.createDefault();
	List<NameValuePair> pairs = new ArrayList<NameValuePair>();
	for(Map.Entry<String,String> entry : map.entrySet())
	{
		pairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
	}
	CloseableHttpResponse response = null;
	try {
		URIBuilder builder = new URIBuilder(url);
		builder.setParameters(pairs);
		HttpGet get = new HttpGet(builder.build());
		response = httpClient.execute(get);
		if(response != null && response.getStatusLine().getStatusCode() == 200)
		{
			HttpEntity entity = response.getEntity();
			result = EntityUtils.toString(entity, "UTF-8");
		}
		return result;
	} catch (URISyntaxException e) {
		e.printStackTrace();
	} catch (ClientProtocolException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}finally {
		try {
			httpClient.close();
			if(response != null)
			{
				response.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	return null;
}

三、 业务调用
1、post请求有参

String jsonString = JSONObject.fromObject(dataParam).toString();
CommonResponse commonResponse = commonService.httpClientConn("http://localhost:82/xm/qq.htm", jsonString);

2、get请求测试(查询路况)

String url = "https://restapi.amap.com/v3/traffic/status/road";
Map<String,String> map = new HashMap<>();
map.put("key","780c1b2ed548ab3cffc4844f9e23a3b1");
map.put("adcode",adcode);
map.put("name",name);
String result = commonService.httpClientGet(url,map);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值