1.使用postForObject
1 2 3 4 5 6 7 8 9
| ServiceInstance serviceInstance = loadBalancerClient.choose("phemsjava"); String url = serviceInstance.getUri() + "/api/filterSiteByMedium"; RestTemplate restTemplate = new RestTemplate(); MultiValueMap<String, String> request = new LinkedMultiValueMap<>(); request.add("sitenolist", sitenolist); request.add("medium_type", mediumtype); List result = restTemplate.postForObject(url, request,List.class);
|
2.设置请求头
在使用restTemplate获取微服务的请求内容的时候,可以设置请求头的内容,主要分为两种方式:
(1) 使用get方法
1 2 3 4 5 6 7 8 9 10 11 12 13
|
Map<String,String> params = new HashMap<>(); params.put("orgCode","900000"); params.put("waybillNo","773011197999686");
HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.add("appId", "app_service");
HttpEntity request = new HttpEntity(requestHeaders);
ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET,request, String.class, params); System.out.println(exchange.getBody());
|
(2) 使用post方法
1 2 3 4 5 6 7 8
| String url = "http://url:port/arius/_sql"; String postBody = "select count(*) from monitor"; HttpHeaders headers = new HttpHeaders(); headers.add("User-Agent", "curl/7.58.0"); HttpEntity<String> entity = new HttpEntity<>(postBody, headers); ResponseEntity<JSONObject> response = restTemplate.postForEntity(url, entity, JSONObject.class); System.out.println(response.getBody().toJSONString());
|
3.401、400错误
当使用restTemplate.postForObject进行请求调用的时候,如果返回的body是一个null,或者状态码是一个401,就有可能报错,这个时候如果想获取到错误消息,而不是直接就跳到catch代码块中,如果做呢?
4.参数接收不到
发送参数并添加header的错误代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| ServiceInstance serviceInstance = loadBalancerClient.choose("databases");
String url = serviceInstance.getUri() + "/wx/sendMsgTimed"; RestTemplate restTemplate = new RestTemplate();
JSONObject post=new JSONObject(); post.put("templateid","DrhF7FOngRmQxYXFb5MzP8CSZtDVaXWtubkI2cYL15E"); post.put("siteno",siteno);
HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<String> request =new HttpEntity<String>(JSONObject.toJSONString(post), headers); JSONObject sendResult = restTemplate.postForObject(url, request,JSONObject.class);
|
使用LinkedMultiValueMap和HttpEntity进行。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| MultiValueMap<String, String> paramMap = new LinkedMultiValueMap<>(); paramMap.add("templateid","DrhF7FOngRmQxYXFb5MzP8CSZtDVaXWtubkI2cYL15E"); paramMap.add("siteno",String.valueOf(siteno));
String dbalias=loginUserHolder.getDbname(); paramMap.add("dbalias",dbalias);
String templateparams=""; paramMap.add("templateparams",templateparams);
HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap> request =new HttpEntity<MultiValueMap>(paramMap, headers);
JSONObject sendResult = restTemplate.postForObject(url, request,JSONObject.class);
|