Java学习|Spring boot微服务架构中,利用RestTemplate调用别人提供的接口

1.自定义RestTemplate 如果是spring框架,需要引入包:
pom文件引用依赖:

org.apache.httpcomponents httpclient 4.5.3

编写一个RestTemplateUtil工具类,继承“RestTemplate”类并重写用到的方法;
如果项目是springboot架构,第一步请忽略。
2.封装RestTemplate访问rest接口
public class RestTemplateUtil { private static final Logger logger = LoggerFactory.getLogger(RestTemplateUtil.class); /** * 1)url: 请求地址; * 2)method: 请求类型(如:POST,PUT,DELETE,GET); * 3)requestEntity: 请求实体,封装请求头,请求内容 * 4)responseType: 响应类型,根据服务接口的返回类型决定 * 5)uriVariables: url中参数变量值 */ public static ResponseEntity sendRequest(String url, HttpMethod method, T requestEntity, Class responseType, Object... uriVariables, String w3Account) { RestTemplate restTemplate=new RestTemplate(); // 设置请求头:ContentType、Token、Cookie、User-Agent HttpHeaders headers = new HttpHeaders(); MediaType type = MediaType.parseMediaType("application/json"); headers.setContentType(type); //这是请求头里的一些参数配置,结合自己的情况填写。 headers.set("userName",w3Account); headers.set("clientType","ISCENARIO"); headers.set("requestId","c021ec9f-11dd-47f7-bb2b-01bae5388779"); HttpEntity entity = new HttpEntity(requestEntity, headers); // 响应默认返回类型为String responseType = (responseType == null ? String.class : responseType); ResponseEntity response = null; try { if(null == uriVariables) { response = restTemplate.exchange(url, method, entity, responseType); } else { response = restTemplate.exchange(url, method, entity, responseType, uriVariables); } } catch (RestClientException e) { logger.error("Send request to the url:{} error.", url); } return response; } }

3.在service层调用封装好的接口。 【Java学习|Spring boot微服务架构中,利用RestTemplate调用别人提供的接口】我这边业务传入的数据是JSON串,如果对象直接传入即可。
//将数据发送给远端 Map,Object> data = https://www.it610.com/article/new HashMap(); String dataStr = JSON.toJSONString(data, true); JSONObject json = JSONObject.parseObject(dataStr); String url = String.valueOf(properties.get("url")); logger.info("=====请求参数=====>>"+url+"\n"+json); ResponseEntity result = RestTemplateUtil.sendRequest(url,HttpMethod.POST,json,Map.class,null,null); logger.info("====调用返回结果=====>>"+result.getBody());

GET/POST请求参数调用方式(封装参数到url)
方式一:这种方式如果遇到参数类型是Long、Integer的会将null值转换为字符串“null”,导致调用出错,可以采取第二种方式
@GetMapping("/getEmployeeInfo") public Map,Object> getEmployeeInfo(@RequestParam("windField") String windField, @RequestParam("windCode") String windCode, @RequestParam("start") Integer start, @RequestParam("length") Integer length){ URI url = null; // 将参数放入键值对类NameValuePair中,再放入集合中,封装url List params = new ArrayList<>(); params.add(new BasicNameValuePair("windField", windField)); params.add(new BasicNameValuePair("windCode", windCode)); params.add(new BasicNameValuePair("start", start.toString())); params.add(new BasicNameValuePair("length", length.toString())); try { url = new URIBuilder().setScheme("http").setHost("172.0.0.1").setPort(8080).setPath("/TEST").setParameters(params).build(); } catch (URISyntaxException e) { e.printStackTrace(); } ResponseEntity responseEntity = HttpClientUtil.sendRequest(url.toString(), HttpMethod.GET, null, Map.class, null); return responseEntity.getBody(); }

方式二:利用占位符去处理参数
@GetMapping("/queryLateInfoCollect") public ResponseData getLateInfoCollect(@RequestParam("flag") Integer flag, @RequestParam("startTime") Long startTime, @RequestParam("endTime") Long endTime, @RequestParam("start") Integer start, @RequestParam("length") Integer length){ String url ="http://172.0.0.1:8008/TEST?flag={flag}&startTime={startTime}&endTime={endTime}&start={start}&length={length}"; ResponseEntity responseEntity = HttpClientUtil.sendRequest(url, HttpMethod.GET, null, ResponseData.class, flag,startTime,endTime,start,length); return responseEntity.getBody(); }

参考:https://www.cnblogs.com/wwct/p/12325173.html

    推荐阅读