java中如何设置代理2014-08-261 前言有时候我们的程序中要提供可以使用代理访问网络,代理的方式包括http、https、ftp、socks代理。比如在IE浏览器设置代理。

那我们在我们的java程序中使用代理呢,有如下两种方式。直接上代码.2 采用设置系统属性
import java.net.Authenticator;import java.net.PasswordAuthentication;import java.util.Properties; public class ProxyDemo1 {public static void main(String[] args) {Properties prop = System.getProperties();// 设置http访问要使用的代理服务器的地址prop.setProperty("http.proxyHost", "183.45.78.31");// 设置http访问要使用的代理服务器的端口prop.setProperty("http.proxyPort", "8080");// 设置不需要通过代理服务器访问的主机,可以使用*通配符,多个地址用|分隔prop.setProperty("http.nonProxyHosts", "localhost|192.168.0.*");// 设置安全访问使用的代理服务器地址与端口// 它没有https.nonProxyHosts属性,它按照http.nonProxyHosts 中设置的规则访问prop.setProperty("https.proxyHost", "183.45.78.31");prop.setProperty("https.proxyPort", "443");// 使用ftp代理服务器的主机、端口以及不需要使用ftp代理服务器的主机prop.setProperty("ftp.proxyHost", "183.45.78.31");prop.setProperty("ftp.proxyPort", "21");prop.setProperty("ftp.nonProxyHosts", "localhost|192.168.0.*");// socks代理服务器的地址与端口prop.setProperty("socksProxyHost", "183.45.78.31");prop.setProperty("socksProxyPort", "1080");// 设置登陆到代理服务器的用户名和密码Authenticator.setDefault(new MyAuthenticator("userName", "Password"));} 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());}} }