博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用httpClient调用接口,参数用map封装或者使用JSON参数,并转换返回结果
阅读量:5907 次
发布时间:2019-06-19

本文共 4112 字,大约阅读时间需要 13 分钟。

这里接口用表存起来,标记请求方式,然后接受参数,消息或者请求参数都可以,

然后先是遍历需要调用的接口,封装参数,再分别调用get与post即可,没有微服务还是得自己写

//消息转发-获取参数中对应参数调用对应接口	public void pmsForward(Map
map){ List
address = forwardAddressHelper.getAddress();//从内存获取转发地址 //封装参数 List
params = new ArrayList
(); Iterator
> iterator = map.entrySet().iterator(); while(iterator.hasNext()){ Map.Entry
next = iterator.next(); params.add(new BasicNameValuePair(next.getKey(),next.getValue())); } address.forEach(x->{ if(StringUtil.isNotEmpty(x.getType())){ if(StringUtil.equals(x.getType(),"GET")){ //get请求 pmsForwardService.getInvoking(x.getAddress(),params); }else if(StringUtil.equals(x.getType(),"POST")){ //post请求 pmsForwardService.postInvoking(x.getAddress(),params); } }else{ log.debug("所请求地址请求方式为空:"+x.getId()+","+x.getAddress()); } }); }

  ,然后是get调用与post调用:

public void getInvoking(String address, List
params) { log.debug("进入get接口调用,参数:"+params+",地址:"+address); CloseableHttpResponse response = null; CloseableHttpClient httpClient = HttpClients.createDefault(); try { URIBuilder builder = new URIBuilder(address); builder.setParameters(params); HttpGet get = new HttpGet(builder.build()); response = httpClient.execute(get); if(response != null && response.getStatusLine().getStatusCode() == 200){ HttpEntity entity = response.getEntity(); log.info("pms消息转发成功,返回结果"+entityToString(entity)); } } catch (Exception e) { e.printStackTrace();log.error("pms消息转发失败"+response.getEntity()); } finally { try { httpClient.close();if(response != null)response.close(); } catch (IOException e) { e.printStackTrace(); } } } @Override public void postInvoking(String address, List
params) { log.debug("进入post接口调用,参数:"+params+",地址:"+address); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost post = new HttpPost(address); CloseableHttpResponse response = null; try { post.setEntity(new UrlEncodedFormEntity(params,"UTF-8")); response = httpClient.execute(post); if(response != null && response.getStatusLine().getStatusCode() == 200){ HttpEntity entity = response.getEntity(); log.info("pms消息转发成功,返回结果"+entityToString(entity)); } } catch (Exception e) { e.printStackTrace();log.error("pms消息转发失败"+response.getEntity()); } finally { try { httpClient.close(); if(response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } }

  ,最后是将response转换成String的方法:

//解析httpclient返回结果,转换成String	private String entityToString(HttpEntity entity) throws IOException {		 String result = null;		 if(entity != null)		 {		 	long lenth = entity.getContentLength();		 	if(lenth != -1 && lenth < 2048){		 		result = EntityUtils.toString(entity,"UTF-8");		 	}else {		 		InputStreamReader reader1 = new InputStreamReader(entity.getContent(), "UTF-8");		 		CharArrayBuffer buffer = new CharArrayBuffer(2048);		 		char[] tmp = new char[1024];		 		int l;		 		while((l = reader1.read(tmp)) != -1) {		 			buffer.append(tmp, 0, l);		 		}		 		result = buffer.toString();		 	}		 }		 return result;	}

  可以debug查看结果了!

还有就是直接使用JSON封装参数:

POST: 只需要设置一下请求头就行了

CloseableHttpClient httpClient = HttpClients.createDefault();		HttpPost post = new HttpPost(address);		post.setHeader("Content-Type", "application/json;charset=UTF-8");		String parameter = GSON.toJson(params);		StringEntity se = new StringEntity(parameter);		se.setContentType(CONTENT_TYPE_TEXT_JSON);		post.setEntity(se);		CloseableHttpResponse response = null;		try {			response = httpClient.execute(post);			if(response != null && response.getStatusLine().getStatusCode() == 200){				HttpEntity entity = response.getEntity();				log.info("消息转发成功,返回结果"+entityToString(entity));			}		} catch (Exception e) {			e.printStackTrace();log.error("消息转发失败"+response.getEntity());		} finally {			try {				httpClient.close();				if(response != null) {					response.close();				}			} catch (IOException e) {				e.printStackTrace();			}		}

  

 

转载于:https://www.cnblogs.com/houzheng/p/9705612.html

你可能感兴趣的文章
在Android(OPhone)模拟器中加载和使用SDCard卡
查看>>
Windows Server 2008 显示隐藏文件 扩展名 和隐藏的文件
查看>>
linux(虚拟机中)与windows共享文件两种方法
查看>>
Exchange 2013信息权限保护之ADRMS安装
查看>>
在图书馆里寻找清静的自我
查看>>
X5平方速算法的证明
查看>>
面试题解(2):loop相关
查看>>
之关于单一职责原则
查看>>
【笔记5】用pandas实现矩阵数据格式的推荐算法 (基于物品的协同)
查看>>
iOS设置拍照retake和use按钮为中文简体
查看>>
Android--通知之Toast
查看>>
【HoorayOS】开源的Web桌面应用框架(第三版 v120421)
查看>>
webview同步cookies
查看>>
lucene LZ4 会将doc存储在一个chunk里进行Lz4压缩 ES的_source便如此
查看>>
[sql] like in 实现参数化查询的问题
查看>>
Spark 架构和组件集的简要概述
查看>>
全局替换字体,开源库更方便!!!
查看>>
使用即时文件初始化提高SQL Server性能
查看>>
MF前传——探索者一号简介
查看>>
.Net开发笔记(六)关于事件(续)
查看>>