使用 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/

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM