最近在项目上遇到okhttp请求需要使用socks5代理的情况,但是不知道如何设置用户名密码,找了很多资料终于发现了方法,现提供代码仅供参考
代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
public class ProxyTest { public static void main(String[] args) throws Exception { Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("127.0.0.1", 1081));
java.net.Authenticator.setDefault(new java.net.Authenticator() { private PasswordAuthentication authentication = new PasswordAuthentication("username", "password".toCharArray());
@Override protected PasswordAuthentication getPasswordAuthentication() { return authentication; } });
OkHttpClient client = new OkHttpClient.Builder().connectTimeout(150, TimeUnit.SECONDS).proxy(proxy).build();
Request request = new Request.Builder().url("http://www.whatismyip.com.tw").get().build(); Response response = client.newCall(request).execute(); System.out.println(response.body().string()); } }
|