由于公司上网实行代理机制,
而最近一段时间又在研究Web上的OpenApi。
没办法一定要使用代理,我之前有文章介绍了httpclient的代理使用方式,
这里介绍基本java的代理使用方式。
最常使用的全局配置代理。
- Properties prop = System.getProperties();
-
- prop.setProperty("http.proxyHost", "10.28.0.254");
-
- prop.setProperty("http.proxyPort", "80");
-
- prop.setProperty("http.nonProxyHosts", "localhost|10.28.0.*");
-
- prop.setProperty("https.proxyHost", "10.28.0.254");
- prop.setProperty("https.proxyPort", "443");
-
-
- prop.setProperty("ftp.proxyHost", "192.168.0.254");
- prop.setProperty("ftp.proxyPort", "2121");
- prop.setProperty("ftp.nonProxyHosts", "localhost|192.168.0.*");
-
- prop.setProperty("socksProxyHost", "192.168.0.254");
- prop.setProperty("socksProxyPort", "8000");
有时代理需要进行身份验证 此时我们需要自己定义一个继承类Authenticator的类
- 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及其之后版本引入新的代理配置,可以满足对特定连接进行配置
- URL url = new URL("http://www.shanhe114.com");
-
- InetSocketAddress addr = new InetSocketAddress("10.28.0.4",
- 8080);
-
- Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
-
- URLConnection conn = url.openConnection(proxy);
- InputStream in = conn.getInputStream();
-
- String content = IOUtils.toString(in);
- System.out.println(content);
JAVA常用的代理设置
原文:http://www.cnblogs.com/langtianya/p/4283566.html