Java 常用的代理设置

package javaproxy;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Properties;

/**
 * 	yanggang@mimvp.com
 * 	http://proxy.mimvp.com
 *	2015-11-09
 */


public class MainTest {

	@SuppressWarnings("serial")
	public static HashMap<String, String> proxyMap = new HashMap<String, String>() {
		{
			put("http", "107.150.96.188:8080");
//			put("https", "162.208.49.45:3127");
//			put("https", "120.195.194.186:80");
			put("https", "120.195.104.157:80");
			put("socks4", "211.236.185.151:1080");
			put("socks5", "218.21.230.156:443");
		}
	};
	
	
	public static void main(String args[]){
		int dataLen = 0;

		// proxy protocol
		System.out.println("+++++++++ proxy protocol +++++++++");
		Iterator<String> it = MainTest.proxyMap.keySet().iterator();
		while(it.hasNext()){
			String key = it.next();
			String value = MainTest.proxyMap.get(key);
			dataLen = proxy_proto(value, key);
			System.out.println(key + " : " + value + " --> " + dataLen);
		}

		// proxy property
		System.out.println("\n+++++++++ proxy property +++++++++");
		Iterator<String> it2 = MainTest.proxyMap.keySet().iterator();
		while(it2.hasNext()){
			String key = it2.next();
			String value = MainTest.proxyMap.get(key);
			dataLen = proxy_prop(value, key);
			System.out.println(key + " : " + value + " --> " + dataLen);
		}

		// proxy socks
		System.out.println("\n++++++++ proxy socks +++++++++++");
		Iterator<String> it3 = MainTest.proxyMap.keySet().iterator();
		while(it3.hasNext()){
			String key = it3.next();
			String value = MainTest.proxyMap.get(key);
			dataLen = proxy_socks(value, key);
			System.out.println(key + " : " + value + " --> " + dataLen);
		}
	}
	
	
	// 设置系统代理,支持全部协议 http,https,socks4,socks5
	private static int proxy_prop(String proxyStr, String proto_type) {
		int dataLen = 0;

		String proxy_ip = proxyStr.split(":")[0];
		String proxy_port = proxyStr.split(":")[1];
		
		Properties prop = System.getProperties();
		
		// http
		if(proto_type.equals("http")){
			prop.setProperty("http.proxyHost", proxy_ip);
			prop.setProperty("http.proxyPort", proxy_port);
			prop.setProperty("http.nonProxyHosts", "localhost|192.168.0.*");
		}
		
		// https
		if(proto_type.equals("https")){
			prop.setProperty("https.proxyHost", proxy_ip);
	        prop.setProperty("https.proxyPort", proxy_port);
		}
        
        // socks
		if(proto_type.equals("socks4") || proto_type.equals("socks5")){
	        prop.setProperty("socksProxyHost", proxy_ip);
	        prop.setProperty("socksProxyPort", proxy_port);
		}
        
        // ftp
		if(proto_type.equals("ftp")){
	        prop.setProperty("ftp.proxyHost", proxy_ip);
	        prop.setProperty("ftp.proxyPort", proxy_port);
	        prop.setProperty("ftp.nonProxyHosts", "localhost|192.168.0.*");
		}
        
//        // auth 设置登陆代理服务器的用户名和密码
//        Authenticator.setDefault(new MyAuthenticator("user", "pwd"));
        
		try{
			URL url = new URL("http://www.baidu.com");		// http://proxy.mimvp.com
			URLConnection conn = url.openConnection();
			conn.setConnectTimeout(30 * 1000);
			
			InputStream in = conn.getInputStream();
			InputStreamReader reader = new InputStreamReader(in);
			char[] ch = new char[1024];
			int len = 0;
			String data = "";
			while((len = reader.read(ch)) > 0) {
				String newData = new String(ch, 0, len);
				data += newData;
			}
			dataLen = data.length();
			
		} catch(Exception e) {
//			e.printStackTrace();
		}
        return dataLen;
	}
	
	static class MyAuthenticator extends Authenticator {
        private String user = "";
        private String password = "";
        public MyAuthenticator(String user, String password) {
            this.user = user;
            this.password = password;
        }
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(user, password.toCharArray());
        }
    }
	
	
	// 使用函数协议,仅支持 HTTP 和 SOCKS5
	private static int proxy_proto(String proxyStr, String proto_type){
		int dataLen = 0;

		String proxy_ip = proxyStr.split(":")[0];
		int proxy_port = Integer.parseInt(proxyStr.split(":")[1]);
		
		try{
			URL url = new URL("http://www.baidu.com");		// http://proxy.mimvp.com
			
			InetSocketAddress addr = new InetSocketAddress(proxy_ip, proxy_port);
			Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
			if(proto_type.equals("socks4") || proto_type.equals("socks5")) {
				proxy = new Proxy(Proxy.Type.SOCKS, addr);
			}
			
			URLConnection conn = url.openConnection(proxy);
			conn.setConnectTimeout(30 * 1000);
			
			InputStream in = conn.getInputStream();
			InputStreamReader reader = new InputStreamReader(in);
			char[] ch = new char[1024];
			int len = 0;
			String data = "";
			while((len = reader.read(ch)) > 0) {
				String newData = new String(ch, 0, len);
				data += newData;
			}
			dataLen = data.length();
			
		} catch(Exception e) {
//			e.printStackTrace();
		}
		return dataLen;
	}
	
	
	// proxy socket,测试用
	private static int proxy_socks(String proxyStr, String proto_type){
		int dataLen = 0;
		Socket socket = null;
		
		String proxy_ip = proxyStr.split(":")[0];
		int proxy_port = Integer.parseInt(proxyStr.split(":")[1]);
		
		try {
			socket = new Socket(proxy_ip, proxy_port);
			
			byte[] ch = new String("GET http://www.baidu.com/ HTTP/1.1\r\n\r\n").getBytes();
			socket.getOutputStream().write(ch);
			socket.setSoTimeout(30 * 1000);
			
			byte[] bt = new byte[1024];
			InputStream in = socket.getInputStream();
			int len = 0;
			String data = "";
			while((len = in.read(bt)) > 0) {
				String newData = new String(bt, 0, len);
				data += newData;
			}
			dataLen = data.length();
		}catch(Exception e) {
//			e.printStackTrace();
		} finally{
			try {
				if(socket != null){
					socket.close();
				}
			} catch (IOException e) {
//				e.printStackTrace();
			}
			socket = null;
		}
		return dataLen;
	}
}


/**
	Run Result : 
	
		+++++++++ proxy protocol +++++++++
		https : 120.195.104.157:80 --> 0
		http : 107.150.96.188:8080 --> 97345
		socks5 : 218.21.230.156:443 --> 97034
		socks4 : 211.236.185.151:1080 --> 0
		
		+++++++++ proxy property +++++++++
		https : 120.195.104.157:80 --> 97173
		http : 107.150.96.188:8080 --> 97087
		socks5 : 218.21.230.156:443 --> 97063
		socks4 : 211.236.185.151:1080 --> 97356
		
		++++++++ proxy socks +++++++++++
		https : 120.195.104.157:80 --> 0
		http : 107.150.96.188:8080 --> 0
		socks5 : 218.21.230.156:443 --> 0
		socks4 : 211.236.185.151:1080 --> 0
*/

 

获取更多代理,请访问米扑代理:

http://proxy.mimvp.com

 

最常使用的全局配置代理

Java代码 

Properties prop = System.getProperties();  
       // HTTP代理的IP设置  
       prop.setProperty("http.proxyHost", "10.28.0.254");  
       // HTTP代理的端口设置  
       prop.setProperty("http.proxyPort", "80");  
       //这里也可以设置不需要使用代理的地址  
       prop.setProperty("http.nonProxyHosts", "localhost|10.28.0.*");  
       //设置HTTPS安全访问的代理服务器地址与端口  
       prop.setProperty("https.proxyHost", "10.28.0.254");  
       prop.setProperty("https.proxyPort", "443");  
//对于安全访问的过滤地址属性同样是http.nonProxyHosts并没有https.nonProxyHosts  
  
       //FTP的代理设置入下  
       prop.setProperty("ftp.proxyHost", "192.168.0.254");  
       prop.setProperty("ftp.proxyPort", "2121");  
       prop.setProperty("ftp.nonProxyHosts", "localhost|192.168.0.*");  
       //SOCKS的代理设置  
       prop.setProperty("socksProxyHost", "192.168.0.254");  
       prop.setProperty("socksProxyPort", "8000");  

有时代理需要进行身份验证 此时我们需要自己定义一个继承类Authenticator的类 

 

Java代码 

public class MyAuthenticator extends Authenticator {  
     private String username = "";  
     private String password = "";  
     public MyAuthenticator(String username, String password) {  
         this.username = username;  
         this.password = password;  
     }  
     protected PasswordAuthentication getPasswordAuthentication() {  
         returnnew PasswordAuthentication(username, password.toCharArray());  
     }  
 }  
  
//设置登陆到代理服务器的用户名和密码  
Authenticator.setDefault(new MyAuthenticator("userName", "Password")); 


当然此种方法可以满足大部分的需求 但是有一定的局限行, 
就是所有的连接通过统一属性进行代理配置的,不能对特定连接进行代理配置。 

JDK5及其之后版本引入新的代理配置,可以满足对特定连接进行配置 

Java代码 

URL url = new URL("http://www.shanhe114.com");  
       //创建代理服务器  
       InetSocketAddress addr = new InetSocketAddress("10.28.0.4",  
               8080);  
       //Proxy proxy = new Proxy(Proxy.Type.SOCKS, addr); //SOCKS代理  
       Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); //HTTP代理  
       //其他方式可以见Proxy.Type属性  
       URLConnection conn = url.openConnection(proxy);  
       InputStream in = conn.getInputStream();  
       //InputStream in = url.openStream();  
       String content = IOUtils.toString(in);  
       System.out.println(content);  

 

参考推荐:

Java 代理使用及代理原理

Java Socket代理访问Web

Java实现Socket5代理服务器

Java 实现socks代理,包含sock4 sock5代理

Java中keySet()返回值的排序问题