本文檔為獲取到代理IP后使用代理的代碼樣例逊谋,供開發(fā)者參考鳞绕。
代碼樣例直接運行無法得到正確的結果京办,因為代碼中的代理地址/端口和應用賬號密碼等信息都是虛構的矛缨,您替換成自己真實的就可以正常運行了斯辰。
如何獲取代理地址/端口和設置代理授權舶担?
使用前提:
1、 已經(jīng)獲取代理地址彬呻。
2衣陶、 已經(jīng)設置代理授權(用戶名/密碼或者IP白名單),去獲取 www.xiaoshitouip.com。
okhttp3和httpClient
package com.example;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.nio.charset.StandardCharsets;
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.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import okhttp3.Authenticator;
import okhttp3.Credentials;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;
public final class Demo {
public static void main(String[] args) throws IOException {
// 從 https://www.xiaoshitouip.com/ 領取后,替換下面的ip和端口
String ip = "代理ip"; // 代理IP地址
int port = 代理端口; // 代理端口
// 替換為自己的用戶名
// 到管理后臺:https://admin.xiaoshitouip.com/proxy/proxy-auth 授權管理頁面添加賬號密碼或者ip白名單
// 設置了ip白名單就不需要設置賬號密碼了
// 使用OKHttp庫
OKHttpProxy.build(ip, port).test();
// OKHttpProxy.build(ip, port, "aaaaaa", "bbbbbb").test(); // 代理認證
// 使用HttpClient庫
// HttpClientProxy.build(ip, port).test();
// HttpClientProxy.build(ip, port, "aaaaaa", "bbbbbb").test(); // 代理認證
}
/**
* OKHttp庫使用代理
*/
static class OKHttpProxy {
String proxyHost;
int proxyPort;
String proxyAccount;
String proxyPwd;
/**
* @param host 代理主機地址
* @param port 代理主機端口
*/
public static OKHttpProxy build(String host, int port) {
OKHttpProxy proxy = new OKHttpProxy();
proxy.proxyHost = host;
proxy.proxyPort = port;
return proxy;
}
/**
* @param host 代理主機地址
* @param port 代理主機端口
* @param acc 代理認證賬號
* @param pwd 代理認證口令
*/
public static OKHttpProxy build(String host, int port, String acc, String pwd) {
OKHttpProxy proxy = new OKHttpProxy();
proxy.proxyHost = host;
proxy.proxyPort = port;
proxy.proxyAccount = acc;
proxy.proxyPwd = pwd;
return proxy;
}
public void test() throws IOException {
String targetUrl = "http://myip.ipip.net";
OkHttpClient client = null;
if (proxyAccount == null || proxyPwd == null) {
client = getHttpClient(proxyHost, proxyPort);
} else {
// 賬號密碼驗證
client = getHttpClient(proxyHost, proxyPort, proxyAccount, proxyPwd);
}
Request request = new Request.Builder()
.url(targetUrl)
.build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
}
/**
* 代理不需要賬號密碼認證的httpClient
*/
private static OkHttpClient getHttpClient(String proxyHost, int proxyPort) {
Proxy proxy = new Proxy(Proxy.Type.HTTP,
new InetSocketAddress(proxyHost, proxyPort));
return new OkHttpClient.Builder()
.proxy(proxy)
.build();
}
/**
* 代理需要賬號密碼認證的httpClient
*/
private static OkHttpClient getHttpClient(String proxyHost,
int proxyPort, String acc, String pwd) {
Proxy proxy = new Proxy(Proxy.Type.HTTP,
new InetSocketAddress(proxyHost, proxyPort));
// 賬號密碼驗證
Authenticator authenticator = new Authenticator() {
@Override
public Request authenticate(Route route, Response resp) throws IOException {
String credential = Credentials.basic(acc, pwd);
return resp.request().newBuilder()
.header("Proxy-Authorization", credential).build();
}
};
return new OkHttpClient.Builder()
.proxy(proxy)
.proxyAuthenticator(authenticator)
.build();
}
}
/**
* HttpClient庫使用代理
*/
static class HttpClientProxy {
String proxyHost;
int proxyPort;
String proxyAccount;
String proxyPwd;
/**
* @param host 代理主機地址
* @param port 代理主機端口
*/
public static HttpClientProxy build(String host, int port) {
HttpClientProxy proxy = new HttpClientProxy();
proxy.proxyHost = host;
proxy.proxyPort = port;
return proxy;
}
/**
* @param host 代理主機地址
* @param port 代理主機端口
* @param acc 代理認證賬號
* @param pwd 代理認證口令
*/
public static HttpClientProxy build(String host,
int port, String acc, String pwd) {
HttpClientProxy proxy = new HttpClientProxy();
proxy.proxyHost = host;
proxy.proxyPort = port;
proxy.proxyAccount = acc;
proxy.proxyPwd = pwd;
return proxy;
}
public void test() throws IOException {
String targetUrl = "http://myip.ipip.net";
CloseableHttpClient client = null;
if (proxyAccount == null || proxyPwd == null) {
client = getHttpClient(proxyHost, proxyPort);
} else {
// 賬號密碼驗證
client = getHttpClient(proxyHost, proxyPort, proxyAccount, proxyPwd);
}
HttpGet httpGet = new HttpGet(targetUrl);
CloseableHttpResponse response = client.execute(httpGet);
String resultStr = EntityUtils.toString(response.getEntity(),
StandardCharsets.UTF_8);
System.out.println(resultStr);
}
/**
* 代理不需要賬號密碼認證的httpClient
*/
private static CloseableHttpClient getHttpClient(String proxyHost, int proxyPort) {
HttpHost proxy = new HttpHost(proxyHost, proxyPort, "HTTP");
return HttpClients.custom()
.setProxy(proxy)
.build();
}
/**
* 代理需要賬號密碼認證的httpClient
*/
private static CloseableHttpClient getHttpClient(String proxyHost,
int proxyPort, String acc, String pwd) {
HttpHost proxy = new HttpHost(proxyHost, proxyPort, "HTTP");
CredentialsProvider provider = new BasicCredentialsProvider();
provider.setCredentials(new AuthScope(proxy),
new UsernamePasswordCredentials(acc, pwd));
return HttpClients.custom()
.setProxy(proxy)
.setDefaultCredentialsProvider(provider)
.build();
}
}
}
pom.xml
<project
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>java-proxy-auth</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.0</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
</dependencies>
</project>