温馨提示:
1. 此样例同时支持访问http和https网页
2. 使用用户名密码访问的情况下,每次请求httpclient不会发送两次进行认证从而导致请求耗时增加,建议使用白名单访问
3. 使用用户名密码验证时必须重写 Authenticator 的 authenticate方法
参考样例
import okhttp3.*; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Proxy; public class TestProxyOKHttpClient { public static void main(String args[]) throws IOException { // 目标网站 String targetUrl = "https://example.com"; // 用户名密码授权 final String username = "username"; final String password = "password"; String ip = "159.138.141.125"; // 代理服务器IP int port = 16875; Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ip, port)); Authenticator authenticator = new Authenticator() { @Override public Request authenticate(Route route, Response response) throws IOException { String credential = Credentials.basic(username, password); return response.request().newBuilder() .header("Proxy-Authorization", credential) .build(); } }; OkHttpClient client = new OkHttpClient.Builder() .proxy(proxy) .proxyAuthenticator(authenticator) .build(); Request request = new Request.Builder() .url(targetUrl) .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3100.0 Safari/537.36") .build(); Response response = client.newCall(request).execute(); System.out.println(response.body().string()); } }