示例代码
import okhttp3.*;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.concurrent.TimeUnit;
public class ProxyTest {
// 代理服务器
final static String proxyHost = "dyn.horocn.com";
final static Integer proxyPort = 50000;
// 代理隧道验证信息
// 用户名和密码可到隧道代理订单页面获取:https://proxy.horocn.com/user-tunnel-orders
// 其中,订单号为用户名
final static String proxyUser = "username";
final static String proxyPass = "password";
static OkHttpClient client = null;
static {
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
Authenticator proxyAuthenticator = new Authenticator() {
public Request authenticate(Route route, Response response) {
String credential = Credentials.basic(proxyUser, proxyPass);
return response.request().newBuilder()
.header("Proxy-Authorization", credential)
.build();
}
};
client = new OkHttpClient().newBuilder()
.followRedirects(false)
.followSslRedirects(false)
.connectTimeout(5, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.SECONDS)
.proxy(proxy)
.proxyAuthenticator(proxyAuthenticator)
.connectionPool(new ConnectionPool(5, 1, TimeUnit.SECONDS))
.build();
}
public static Response doGet() throws IOException {
// 要访问的目标页面
String targetUrl = "https://www.baidu.com/";
Request request = new Request.Builder()
.url(targetUrl)
.build();
return client.newCall(request).execute();
}
public static void main(String[] args) throws IOException {
System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
Response response1 = doGet();
System.out.println("GET请求返回结果:");
assert response1.body() != null;
System.out.println(response1.body().string());
}
}
测试环境
openjdk-12.0.2
okhttp-3.14.9
注意点
1、出现错误:unexpected end of stream on unknown
请检查下用户名和密码是否准确
请检查下订单是否过期
转载请注明
头条号 - 蜻蜓软件
微信公众号:蜻蜓软件(qingtingsoft)