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<String> 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<String, Object> paramMap = new HashMap<String, Object>();
Map<String, Object> paramMap = new LinkedHashMap<String, Object>();

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

MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
 

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

// 3、使用exchange请求接口
ResponseEntity<String> 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<String, Object> paramMap = new HashMap<String, Object>();
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<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(null,headers);
ResponseEntity<String> response2 = template.exchange(url, HttpMethod.GET, httpEntity, String.class,paramMap);

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

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

        Map<String, Object> postBody = Maps.newHashMap();
        postBody.put("userInfo", userInfo);

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

         try {
             ResponseEntity<String> 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);
        }

 

 

 

 

 

 

  • 11
    点赞
  • 50
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
在使用`restTemplate`添加请求body时,可以使用以下几种方法: 1. 使用`postForObject`方法发送POST请求并获取响应结果,将请求参数以`MultiValueMap`的形式存储在`paramMap`中,然后将`paramMap`作为参数传入`postForObject`方法中。例如: ``` MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>(); paramMap.add("dt", "20190225"); String result = template.postForObject(url, paramMap, String.class); ``` 2. 使用`postForEntity`方法发送POST请求并获取响应结果。首先创建`HttpHeaders`和`HttpEntity`对象,将请求参数以`MultiValueMap`的形式存储在`paramMap`中,然后将`paramMap`和`headers`作为参数传入`HttpEntity`构造函数中,最后将`HttpEntity`对象作为参数传入`postForEntity`方法中。例如: ``` HttpHeaders headers = new HttpHeaders(); HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(paramMap, headers); ResponseEntity<String> response2 = template.postForEntity(url, httpEntity, String.class); ``` 3. 使用`exchange`方法发送POST请求并获取响应结果。首先创建`HttpHeaders`和`HttpEntity`对象,将请求参数以`MultiValueMap`的形式存储在`paramMap`中,然后将`paramMap`和`headers`作为参数传入`HttpEntity`构造函数中,最后将`HttpEntity`对象作为参数传入`exchange`方法中。例如: ``` HttpHeaders headers = new HttpHeaders(); HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(paramMap, headers); ResponseEntity<String> response3 = template.exchange(url, HttpMethod.POST, httpEntity, String.class); ``` 以上是使用`restTemplate`添加请求body的几种方法,根据具情况选择适合的方法进行使用。 <span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [RestTemplate 添加请求头headers和请求body](https://blog.csdn.net/u011138533/article/details/87920632)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [spring-boot-swagger.7z](https://download.csdn.net/download/bethzhang/11349186)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值