- import java.io.ByteArrayOutputStream;
- import java.io.InputStream;
- import java.NET.Authenticator;
- import java.NET.HttpURLConnection;
- import java.NET.InetSocketAddress;
- import java.NET.PasswordAuthentication;
- import java.NET.Proxy;
- import java.NET.URL;
- import java.util.Random;
- class ProxyAuthenticator extends Authenticator {
- private String user, password;
- public ProxyAuthenticator(String user, String password) {
- this.user = user;
- this.password = password;
- }
- protected PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication(user, password.toCharArray());
- }
- }
- /**
- * 注意: 下面代码仅仅实现 HTTP 请求链接, 每一次请求都是无状态保留的, 仅仅是这次请求是更换 IP 的, 如果下次请求的 IP 地址会改变
- * 如果是多线程访问的话, 只要将下面的代码嵌入到你自己的业务逻辑里面, 那么每次都会用新的 IP 进行访问, 如果担心 IP 有重复,
- * 自己可以维护 IP 的使用情况, 并做校验.
- */
- public class Demo {
- public static void main(String args[]) throws Exception {
- // 要访问的目标页面
- String targetUrl = "http://httpbin.org/ip";
- // 代理服务器
- String proxyServer = "t.16yun.cn";
- int proxyPort = 31111;
- // 代理隧道验证信息
- String proxyUser = "username";
- String proxyPass = "password";
- try {
- URL url = new URL(targetUrl);
- Authenticator.setDefault(new ProxyAuthenticator(proxyUser, proxyPass));
- // 创建代理服务器地址对象
- InetSocketAddress addr = new InetSocketAddress(proxyServer, proxyPort);
- // 创建 HTTP 类型代理对象
- Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
- // 设置通过代理访问目标页面
- HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy);
- // 设置 Proxy-Tunnel
- // Random random = new Random();
- // int tunnel = random.nextInt(10000);
- // connection.setRequestProperty("Proxy-Tunnel",String.valueOf(tunnel));
- // 解析返回数据
- byte[] response = readStream(connection.getInputStream());
- System.out.println(new String(response));
- } catch (Exception e) {
- System.out.println(e.getLocalizedMessage());
- }
- }
- /**
- * 将输入流转换成字符串
- *
- * @param inStream
- * @return
- * @throws Exception
- */
- public static byte[] readStream(InputStream inStream) throws Exception {
- ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
- byte[] buffer = new byte[1024];
- int len = -1;
- while ((len = inStream.read(buffer)) != -1) {
- outSteam.write(buffer, 0, len);
- }
- outSteam.close();
- inStream.close();
- return outSteam.toByteArray();
- }
- }
来源: http://www.bubuko.com/infodetail-3095965.html