`
Franciswmf
  • 浏览: 779036 次
  • 性别: Icon_minigender_1
  • 来自: 上海
文章分类
社区版块
存档分类
最新评论

restTemplate调用GET/POST接口

 
阅读更多
org.springframework.web.client.RestTemplate以GET或POST方式调用微服务接口:
	public String invokeService(HttpMethod httpMethod, UrlSe urlSe, String getParams, MultiValueMap<String, String> postParams, String token){
		if(null == httpMethod || null==urlSe){
			LOG.info(Constants.INPUT_PARAMS_ILLEGAL);
			throw new BusinessException(Constants.INPUT_PARAMS_ILLEGAL);
		}
		URI uri = util.getServiceUrl(urlSe.getService(), Constants.ERROR_URL);
		String url=uri.toString() + urlSe.getUrl();
		String resultString=null;
		//header
		HttpHeaders httpHeaders = new HttpHeaders();
		if(StringUtils.isNotBlank(token)){
			httpHeaders.add(Constants.TOKEN, token);
		}
		if(HttpMethod.GET.equals(httpMethod)){
			//get方法
			httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
			//"?a=" + 1+"&b="+2
			url += getParams;
			HttpEntity<String> requestEntity = new HttpEntity<String>(httpHeaders);
			resultString= restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class).getBody();
		}else if(HttpMethod.POST.equals(httpMethod)){
			//post方法
			HttpEntity<MultiValueMap<String, String>> httpEntity=new HttpEntity<>(postParams, httpHeaders);
			resultString = restTemplate.postForEntity(url, httpEntity, String.class).getBody();
		}else {
			LOG.info(Constants.INPUT_PARAMS_ILLEGAL);
			throw new BusinessException(Constants.INPUT_PARAMS_ILLEGAL);
		}
		LOG.info("resultString={}", resultString);
		//处理响应数据: 只返回result部分
		JSONObject jsonObject = JSONObject.fromObject(resultString);
 		if(!jsonObject.isNullObject()){
 			//只返回result部分
			String result = jsonObject.getString(Constants.RESULT);
			return result;
		}
		return null;
	}


POST调用:
MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
requestEntity.add("a", 1);
requestEntity.add("b", 2);
String jsonString=tools.invokeService(HttpMethod.POST, UrlSe.USER_INFO, null, requestEntity, null);
if(StringUtils.isBlank(jsonString)){
	LOG.info(ValueConstants.USER_INFO_NOT_FOUND);
	throw new BusinessException(ValueConstants.USER_INFO_NOT_FOUND);
}


GET调用
String getParams="?a="+1;
String jsonString=commonTools.invokeService(HttpMethod.GET, UrlSource.QUERY_ROLE_ID, getParams, null, token);
if(StringUtils.isBlank(jsonString)){
	LOG.info(ValueConstants.INPUT_PARAMS_ILLEGAL);
	throw new BusinessException(ValueConstants.INPUT_PARAMS_ILLEGAL);
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics