• 2024-04-18
宇哥博客 后端开发 Java中HttpClient代理proxy配置帐号密码

Java中HttpClient代理proxy配置帐号密码

通过代理IP请求目标地址,适用于数据采集、爬虫等。

所用到的相关 jar 包:

  • httpclient-4.5.3.jar
  • httpcore-4.4.6.jar

以下是部分代码:

public static void main(String[] args)  throws Exception {
	String ProxyAddr = "代理地址"; //代理地址
	int ProxyPort = 8888;//端口
	String ProxyUser = "帐号";//帐号
	String ProxyPasswd = "密码";//密码
	
	CredentialsProvider credsProvider = new BasicCredentialsProvider();
	credsProvider.setCredentials(
			new AuthScope(ProxyAddr, ProxyPort),
			new UsernamePasswordCredentials(ProxyUser, ProxyPasswd));
	CloseableHttpClient httpclient = HttpClients.custom()
			.setDefaultCredentialsProvider(credsProvider).build();
	try {
		HttpHost proxy = new HttpHost(ProxyAddr, ProxyPort);

		RequestConfig config = RequestConfig.custom()
			.setConnectTimeout(300000).setConnectionRequestTimeout(100000).setSocketTimeout(300000)
			.setProxy(proxy)
			.build();
		HttpGet httpget = new HttpGet("https://www.baidu.com");
		httpget.setConfig(config);
		httpget.setHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36");

		CloseableHttpResponse response = httpclient.execute(httpget);
		try {
			System.out.println("状态码:"+response.getStatusLine().getStatusCode());
			System.out.println("结果:"+EntityUtils.toString(response.getEntity(), "utf-8"));
		} finally {
			response.close();
		}
	} finally {
		httpclient.close();
	}
}

如果不需要验证帐号、密码,把下面这部分代码:

改成:
CloseableHttpClient httpclient = HttpClients.custom().build();

更多

httpclient-4.5.3.jar 下载地址:https://search.maven.org/artifact/org.apache.httpcomponents/httpclient/4.5.3/jar

httpcore-4.4.6.jar下载地址:https://search.maven.org/artifact/org.apache.httpcomponents/httpcore

本文来自网络,不代表本站立场,转载请注明出处。http://www.ygbks.com/3671.html

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

返回顶部