温馨提示:
1. 此样例同时支持访问http和https网页
2. 使用用户名密码验证时必须使用java.net.Authenticator.setDefault()方法
参考样例
import okhttp3.*; import java.io.IOException; import java.net.InetSocketAddress; import java.net.PasswordAuthentication; 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.168.147.125"; // 代理服务器IP int port = 16818; Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(ip, port)); java.net.Authenticator.setDefault(new java.net.Authenticator(){//通过设置一个全局的Authenticator,实现socks设置Authenticator用户名密码 private PasswordAuthentication authentication = new PasswordAuthentication(username, password.toCharArray()); @Override protected PasswordAuthentication getPasswordAuthentication() { return authentication; } }); OkHttpClient client = new OkHttpClient.Builder() .proxy(proxy) .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()); } }