注册
登录
 文档中心 产品介绍 开发指南 API接口 代码样例 使用帮助
Java使用resttemplate调用Http代理IP的代码样例
站大爷 官方 2024-01-20 1491 浏览

温馨提示:

1.  此样例同时支持访问http和https网页

2.  使用用户名密码访问的情况下,每次请求httpclient会发送两次进行认证从而导致请求耗时增加,建议使用终端IP授权访问

3.  依赖包下载:

     httpclient-4.5.6.jar   

     httpcore-4.4.10.jar

     commons-codec-1.10.jar

     commons-logging-1.2.jar

     spring-web-5.2.24.jar

     spring-beans-5.2.24.jar

     spring-core-5.2.24.jar

     spring-jcl-5.2.24.jar


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);
	}
}


立即注册站大爷用户,免费试用全部产品
立即注册站大爷用户,免费试用全部产品