Java使用resttemplate调用Http代理IP的代码样例
站大爷
官方
2024-01-20
1491 浏览
温馨提示:
1. 此样例同时支持访问http和https网页
2. 使用用户名密码访问的情况下,每次请求httpclient会发送两次进行认证从而导致请求耗时增加,建议使用终端IP授权访问
3. 依赖包下载:
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.ProxyAuthenticationStrategy;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
public class TestProxyRestTemplate {
// 目标网站
private static String pageUrl = "https://example.com";
// 代理服务器IP、端口号
private static String proxyHost = "159.138.141.125";
private static Integer proxyPort = 18916;
// 用户名密码授权
private static String ProxyUser = "username";
private static String Proxypass = "password";
public static void main(String[] args) {
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(proxyHost, proxyPort),
new UsernamePasswordCredentials(ProxyUser, Proxypass)
);
HttpHost proxy = new HttpHost(proxyHost, proxyPort);
HttpClientBuilder clientBuilder = HttpClientBuilder.create();
clientBuilder.useSystemProperties();
clientBuilder.setProxy(proxy);
clientBuilder.setDefaultCredentialsProvider(credsProvider);
clientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
CloseableHttpClient client = clientBuilder.build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setHttpClient(client);
RestTemplate restTemplate = new RestTemplate();
restTemplate.setRequestFactory(factory);
String result = restTemplate.getForObject(pageUrl, String.class);
System.out.println(result);
}
}