zoukankan      html  css  js  c++  java
  • 使用 Spring RestTemplate 调用 rest 服务时自定义请求头(custom HTTP headers)

            在 Spring 3.0 中可以通过  HttpEntity 对象自定义请求头信息,如:

    private static final String APPLICATION_PDF = "application/pdf";
     
    RestTemplate restTemplate = new RestTemplate();
     
    @Test
    public void acceptHeaderUsingHttpEntity() throws Exception {
      HttpHeaders headers = new HttpHeaders();
      headers.setAccept(singletonList(MediaType.valueOf(APPLICATION_PDF)));
     
      ResponseEntity<byte[]> response = restTemplate.exchange("http://example.com/file/123",
          GET,
          new HttpEntity<byte[]>(headers),
          byte[].class);
     
      String responseText = PdfTextExtractor.getTextFromPage(new PdfReader(response.getBody()), 1);
      assertEquals("Some text in PDF file", responseText);
    }

            在 Spring 3.1 中有了一个更强大的替代接口  ClientHttpRequestInterceptor,这个接口只有一个方法: intercept(HttpRequest request, byte[] body,     ClientHttpRequestExecution execution),下面是一个例子:

    private static final String APPLICATION_PDF = "application/pdf";
     
    RestTemplate restTemplate = new RestTemplate();
     
    @Test
    public void acceptHeaderUsingHttpRequestInterceptors() throws Exception {
      ClientHttpRequestInterceptor acceptHeaderPdf = new AcceptHeaderHttpRequestInterceptor(
          APPLICATION_PDF);
     
      restTemplate.setInterceptors(singletonList(acceptHeaderPdf));
     
      byte[] response = restTemplate.getForObject("http://example.com/file/123", byte[].class);
     
      String responseText = PdfTextExtractor.getTextFromPage(new PdfReader(response), 1);
      assertEquals("Some text in PDF file", responseText);
    }
     
    class AcceptHeaderHttpRequestInterceptor implements ClientHttpRequestInterceptor {
      private final String headerValue;
     
      public AcceptHeaderHttpRequestInterceptor(String headerValue) {
        this.headerValue = headerValue;
      }
     
      @Override
      public ClientHttpResponse intercept(HttpRequest request, byte[] body,
          ClientHttpRequestExecution execution) throws IOException {
     
        HttpRequestWrapper requestWrapper = new HttpRequestWrapper(request);
        requestWrapper.getHeaders().setAccept(singletonList(MediaType.valueOf(headerValue)));
     
        return execution.execute(requestWrapper, body);
      }
    }


    原文:http://svenfila.wordpress.com/2012/01/05/resttemplate-with-custom-http-headers/

  • 相关阅读:
    协议分析 - DHCP协议解码详解
    在SqlServer2000的视图中小心使用*符号
    sql 将 varchar 值转换为数据类型为 int 的列时发生语法错误 的解决办法
    LECCO SQL Expert工具之优化sql语句
    css+js简单应用
    对任何一天是星期几算法的实现
    asp.net ajax 1.0 出现"sys"未定义解决方法
    js日历脚本
    在ASP.NET中重写URL
    在ASP.NET中重写URL (续篇)
  • 原文地址:https://www.cnblogs.com/snake-hand/p/3151331.html
Copyright © 2011-2022 走看看