RestTemplate 添加请求头headers和请求体body

//headers & cookie
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);

headers.add("basecret", config.getBasecret());
headers.add("baid", config.getBaid());

List cookies = new ArrayList<>();
cookies.add("COOKIE_USER" + Strings.nullToEmpty(config.getCookie()));
headers.put(HttpHeaders.COOKIE, cookies);

1、 调用postForObject方法   2、使用postForEntity方法  3、调用exchange方法

    postForObject和postForEntity方法的区别主要在于可以在postForEntity方法中设置header的属性,当需要指定header的属性值的时候,使用postForEntity方法。exchange方法和postForEntity类似,但是更灵活,exchange还可以调用get请求。使用这三种方法传递参数,Map不能定义为以下两种类型

Map paramMap = new HashMap();
Map paramMap = new LinkedHashMap();

把Map类型换成LinkedMultiValueMap后,参数成功传递到后台

MultiValueMap paramMap = new LinkedMultiValueMap();
 

MultiValueMap paramMap = new LinkedMultiValueMap();
paramMap.add("dt", "20190225");
 
// 1、使用postForObject请求接口
String result = template.postForObject(url, paramMap, String.class);
 
// 2、使用postForEntity请求接口
HttpHeaders headers = new HttpHeaders();
HttpEntity> httpEntity = new HttpEntity>(paramMap,headers);
ResponseEntity response2 = template.postForEntity(url, httpEntity, String.class);

// 3、使用exchange请求接口
ResponseEntity response3 = template.exchange(url, HttpMethod.POST, httpEntity, String.class);

4、get方法

如果是get请求,又想要把参数封装到map里面进行传递的话,Map需要使用HashMap,且url需要使用占位符,如下:

RestTemplate restTemplate2 = new RestTemplate();
String url = "http://127.0.0.1:8081/interact/getData?dt={dt}&ht={ht}";
       
// 封装参数,这里是HashMap
Map paramMap = new HashMap();
paramMap.put("dt", "20190225");
paramMap.put("ht", "10");
 
//1、使用getForObject请求接口
String result1 = template.getForObject(url, String.class, paramMap);
System.out.println("result1====================" + result1);
 
//2、使用exchange请求接口
HttpHeaders headers = new HttpHeaders();
headers.set("id", "lidy");
HttpEntity> httpEntity = new HttpEntity>(null,headers);
ResponseEntity response2 = template.exchange(url, HttpMethod.GET, httpEntity, String.class,paramMap);

5、如果post请求体是个Json的表单

        //JSONObject userInfo = new JSONObject();
        Map userInfo = Maps.newHashMap();
    
        userInfo.put("phone", accountForm.getPhone());
        
        userInfo.put("job", accountForm.getJob());
        userInfo.put("email", accountForm.getEmail());
       

        Map postBody = Maps.newHashMap();
        postBody.put("userInfo", userInfo);

        HttpEntity requestEntity = new HttpEntity<>(postBody, headers);

         try {
             ResponseEntity result = restTemplate.postForEntity(config.getCreateWithAuthUrl(), requestEntity, String.class);
             JsonNode jsonNode = JsonUtils.toJsonNode(result.getBody());
             if (jsonNode.get("errno").asInt() == 200 || jsonNode.get("errno").asInt() == 505) {
                 return true;
             }

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

 

 

 

 

 

 

你可能感兴趣的:(JAVA核心技术系列)