1. 概述
在本簡短教程中,我們將學習如何使用 RestTemplate 向代理服務器發送請求。
2. 依賴項
首先,RestTemplateCustomizer 使用 HttpClient 類連接到代理。
要使用該類,我們需要將 Apache 的 httpcore 依賴項添加到我們的 Maven pom.xml 文件中:
<dependency>
<groupId>org.apache.httpcomponents.core5</groupId>
<artifactId>httpcore5</artifactId>
<version>5.2.1</version>
</dependency>
或者添加到我們的 Gradle build.gradle 文件中:
compile 'org.apache.httpcomponents.core5:httpcore5:5.2.1'
3. 使用 SimpleClientHttpRequestFactory
使用 RestTemplate 發送請求到代理非常簡單。我們只需要調用 從 SimpleClientHttpRequestFactory 中調用 setProxy(java.net.Proxy)
首先,我們通過配置 SimpleClientHttpRequestFactory:
Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress(PROXY_SERVER_HOST, PROXY_SERVER_PORT));
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setProxy(proxy);
然後,我們繼續將請求工廠實例傳遞到 RestTemplate 構造函數中:
RestTemplate restTemplate = new RestTemplate(requestFactory);
最後,一旦我們構建了 RestTemplate,我們就可以使用它來執行代理請求:
ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://httpbin.org/get", String.class);
assertThat(responseEntity.getStatusCode(), is(equalTo(HttpStatus.OK)));
4. 使用 RestTemplateCustomizer
另一種方法是使用 RestTemplateCustomizer 與 RestTemplateBuilder 構建自定義的 RestTemplate。
讓我們開始定義 ProxyCustomizer:
class ProxyCustomizer implements RestTemplateCustomizer {
@Override
public void customize(RestTemplate restTemplate) {
HttpHost proxy = new HttpHost(PROXY_SERVER_HOST, PROXY_SERVER_PORT);
HttpClient httpClient = HttpClientBuilder.create()
.setRoutePlanner(new DefaultProxyRoutePlanner(proxy))
.build();
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient));
}
}
之後,我們構建我們的自定義 RestTemplate:
RestTemplate restTemplate = new RestTemplateBuilder(new ProxyCustomizer()).build();
最後,我們使用 RestTemplate 發送通過代理服務器進行的請求:
ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://httpbin.org/get", String.class);
assertThat(responseEntity.getStatusCode(), is(equalTo(HttpStatus.OK)));
5. 結論
在本教程中,我們探討了兩種使用 RestTemplate 向代理髮送請求的不同方法。
首先,我們學習瞭如何通過使用 SimpleClientHttpRequestFactory 構建的 RestTemplate 發送請求。然後,我們學習瞭如何使用 RestTemplateCustomizer 完成同樣的操作,該方法是根據 文檔 推薦的方法。