注册
登录
 文档中心 产品介绍 开发指南 API接口 代码样例 使用帮助
Java使用okhttp3调用Socks5代理IP的代码样例
站大爷 官方 2024-01-20 1853 浏览

温馨提示:

1.  此样例同时支持访问http和https网页

2.  使用用户名密码验证时必须使用java.net.Authenticator.setDefault()方法

3.  添加依赖


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());

	}
}


立即注册站大爷用户,免费试用全部产品
立即注册站大爷用户,免费试用全部产品