Java 设置代理IP 访问网络

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/aaa000830/article/details/78487761

一. 工具准备

为了能够验证Java程序是否真的通过代理访问网络,还是准备一个代理工具:fiddler,很好的一个能监视http、https的debug工具,附件中有。

二. 开始

先写一段简单的网络访问程序,如下:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;

public class MyClass {

	public static String ParseStream(InputStream stream) {
		StringBuilder builder = new StringBuilder("");
		try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) {
			String strtmp;
			try {
				strtmp = reader.readLine();
				while (null != strtmp) {
					builder.append(strtmp);
					builder.append("\n");
					strtmp = reader.readLine();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return builder.toString();
	}

	public static void main(String[] args) {
		try {
			URL url = new URL("http://1212.ip138.com/ic.asp");
			URLConnection connection = url.openConnection();
			System.out.println(ParseStream(connection.getInputStream()));
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
}

同时,打开fiddler工具,运行该程序,发现fiddler中并没有任何显示,原因:jvm的网络连接会绕过fiddler的代理

所以我们要设置fiddler为本机代理服务器,IP:localhost,Port:8888

1.直接在jvm参数中设置该代理服务器


说明:http代理为 -Dhttp.proxyHost=localhost -Dhttp.proxyPort=8888,https代理为 -Dhttps.proxyHost=localhost -Dhttps.proxyPort=8888

然后再次运行上面的程序,发现fiddler中有显示,说明代理设置成功

2.代码中设置全局代理

去掉jvm参数中的代理设置,在代码中设置,如下:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;

public class MyClass {

	public static String ParseStream(InputStream stream) {
		StringBuilder builder = new StringBuilder("");
		try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) {
			String strtmp;
			try {
				strtmp = reader.readLine();
				while (null != strtmp) {
					builder.append(strtmp);
					builder.append("\n");
					strtmp = reader.readLine();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return builder.toString();
	}

	public static void main(String[] args) {
	  System.setProperty("http.proxyHost", "localhost"); 
		System.setProperty("http.proxyPort", "8888"); 
		System.setProperty("https.proxyHost", "localhost");
		System.setProperty("https.proxyPort", "8888");
		try {
			URL url = new URL("http://1212.ip138.com/ic.asp");
			URLConnection connection = url.openConnection();
			System.out.println(ParseStream(connection.getInputStream()));
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
}

3.设置Proxy对象

同样是通过代码来设置,如下:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Proxy.Type;
import java.net.ProxySelector;
import java.net.SocketAddress;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class MyClass {

	public static String ParseStream(InputStream stream) {
		StringBuilder builder = new StringBuilder("");
		try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) {
			String strtmp;
			try {
				strtmp = reader.readLine();
				while (null != strtmp) {
					builder.append(strtmp);
					builder.append("\n");
					strtmp = reader.readLine();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return builder.toString();
	}

	public static void main(String[] args) {
	  SocketAddress address = new InetSocketAddress("localhost", 8888);
		Proxy proxy = new Proxy(Type.HTTP, address);
		try {
			URL url = new URL("http://1212.ip138.com/ic.asp");
			URLConnection connection = url.openConnection(proxy);
			System.out.println(ParseStream(connection.getInputStream()));
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
}

4.基于Proxy对象的方式来设置 ProxySelector

由于单纯的设置Proxy 对象有点麻烦,每次都要设置,所以可以一次性设置所有的Proxy 对象,程序自动使用合适的Proxy 对象

通过 ProxySelector 选择器来完成,这个选择器是个抽象类,需要实现两个方法,select 方法是用于列举出你所有用到的Proxy 对象,让程序来自动选择的,这个方法

返回一个列表,意思是从列表的第一个代理开始尝试,如果第一个不行,就尝试第二个,直到最后,如果都不行就调用第二个需要实现的方法 connectFailed,即通知

程序这个链接无法通过设置的代理访问,好了,代码如下:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Proxy.Type;
import java.net.ProxySelector;
import java.net.SocketAddress;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class MyClass {

  public static class MyProxy extends ProxySelector {

		private List<URI> failed = new ArrayList<>();

		@Override
		public List<Proxy> select(URI uri) {
			List<Proxy> result = new ArrayList<>();
			if (failed.contains(uri) || (!"https".equalsIgnoreCase(uri.getScheme())
					&& !"http".equalsIgnoreCase(uri.getScheme()))) {
				result.add(Proxy.NO_PROXY);
			} else {
				SocketAddress address = new InetSocketAddress("localhost", 8888);
				Proxy proxy = new Proxy(Type.HTTP, address);
				result.add(proxy);
			}
			return result;
		}

		@Override
		public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
			failed.add(uri);
		}

	}

	public static String ParseStream(InputStream stream) {
		StringBuilder builder = new StringBuilder("");
		try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) {
			String strtmp;
			try {
				strtmp = reader.readLine();
				while (null != strtmp) {
					builder.append(strtmp);
					builder.append("\n");
					strtmp = reader.readLine();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return builder.toString();
	}

	public static void main(String[] args) {
		try {
			URL url = new URL("http://1212.ip138.com/ic.asp");
			URLConnection connection = url.openConnection();
			System.out.println(ParseStream(connection.getInputStream()));
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
}

至此:有问题欢迎评论指正!





展开阅读全文

没有更多推荐了,返回首页