【问题标题】:Adding headers to postForObject() method of RestTemplate in spring在 Spring 中向 RestTemplate 的 postForObject() 方法添加标头
【发布时间】:2018-02-19 21:30:03
【问题描述】:

我正在使用以下方法调用网络服务。

ResponseBean responseBean = getRestTemplate()
    .postForObject(url, customerBean, ResponseBean.class);

现在我的要求发生了变化。我想随请求发送 2 个标头。 我该怎么做?

Customer bean 是一个类,其中包含将用作请求正文的所有数据。

这种情况下如何添加标题?

【问题讨论】:

    标签: spring rest web-services restful-authentication


    【解决方案1】:

    您可以将HttpEntity<T> 用于您的目的。例如:

    CustomerBean customerBean = new CustomerBean();
    // ...
    
    HttpHeaders headers = new HttpHeaders();
    headers.set("headername", "headervalue");      
    
    HttpEntity<CustomerBean> request = new HttpEntity<>(customerBean, headers);
    
    ResponseBean response = restTemplate.postForObject(url, request, ResponseBean.class); 
    

    【讨论】:

      【解决方案2】:

      只需使用org.springframework.http.HttpHeaders 创建您的标头并添加CustomBean。某事看起来像:

       CustomerBean customerBean = new CustomerBean();
       HttpHeaders headers = new HttpHeaders();
      
      // can set the content Type
      headers.setContentType(MediaType.APPLICATION_JSON);
      
      //Can add token for the authorization
      headers.add(HttpHeaders.AUTHORIZATION, "Token");
      
      headers.add("headerINfo", "data");
      
      //put your customBean to header
      HttpEntity< CustomerBean > entity = new HttpEntity<>(customBean, headers);
      //can post and get the ResponseBean 
      restTemplate.postForObject(url, entity, ResponseBean.class);
      //Or return the ResponseEntity<T>  
      

      希望对您有所帮助。

      【讨论】:

        猜你喜欢
        • 2019-03-20
        • 2012-07-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-01
        • 2018-05-15
        • 2010-09-19
        相关资源
        最近更新 更多