Java通过代理服务器访问外部网络

今天闲来无事,看同事在做IIS监控内容,我想咱也没事看看HTTP什么的,在网上看,觉得Apache的httpclient开源包不错,封装了很多http操作,但目前我还没有仔细研究,只是用简单的socket连接,于是在网上搜罗代码,发现有两种方式可以进行访问,不过第二种目前我没有调试成功,第一种没有问题,因为我就是用公司的代理服务器上网的。

代码如下:

ExpandedBlockStart.gif 代码
import  java.io.BufferedInputStream;
import  java.io.BufferedOutputStream;
import  java.io.FileOutputStream;
import  java.io.IOException;
import  java.io.InputStream;
import  java.io.OutputStream;
//  import java.net.Authenticator;
import  java.net.HttpURLConnection;
//  import java.net.PasswordAuthentication;
import  java.net.URL;
import  java.net.URLConnection;
//  Base64编码用
import  sun.misc.BASE64Encoder;

public   class  ProxyTest {
    
//  这个是第二种,不过目前我没调通
     /**
     * 对代理进行初始设置
     * 
     * 
@param  host
     *            代理服务器的IP
     * 
@param  port
     *            代理服务器的端口
     * 
@param  username
     *            连接代理服务器的用户名
     * 
@param  password
     *            连接代理服务器的密码
     
*/
    
public   static   void  initProxy(String host,  int  port,  final  String username,

    
final  String password) {
        
//  设置一个默认的验证器
         /*
         * Authenticator.setDefault(new Authenticator() {
         * 
         * protected PasswordAuthentication getPasswordAuthentication() {
         * 
         * return new PasswordAuthentication(username,
         * 
         * new String(password).toCharArray());
         * 
         * }
         * 
         * });
         
*/
        
//  设置对HTTP进行代理,key可以写成http.proxyXxxx或proxyXxxx两种形式
        
//  System.setProperty("http.proxyType", "4");
        System.setProperty( " http.proxyPort " , Integer.toString(port));

        System.setProperty(
" http.proxyHost " , host);

        System.setProperty(
" http.proxySet " " true " );

    }

    
public   static   void  main(String[] args)  throws  IOException {
        
//  main中的是第二种,通过在头部加入Proxy-Authentication信息,通过Base64编码传递
        
//  String ftpurl = "ftp: // 204.2.225.157/favicon.ico";
        
//  String ftpurl = "ftp: // 204.2.225.157/robots.txt";
         /*
         * String httpurl = "
http://www.sina.com ";
         * 
         * String proxy = "192.168.1.95";// 代理服务器IP
         * 
         * int port = 80;// 代理服务器端口
         * 
         * String username = "dizh";// 连接代理服务器的用户名
         * 
         * String password = "dizhuang1984HIT*";// 连接代理服务器的密码
         * 
         * String temp = "D:/temp";// 存放文件的临时目录
         * 
         * initProxy(proxy, port, username, password);
         * 
         * // test(ftpurl, temp); test(httpurl, temp);
         
*/
        
try  {
            System.setProperty(
" http.proxySet " " true " );
            System.setProperty(
" http.proxyHost " " 192.168.1.95 " );
            System.setProperty(
" http.proxyPort " " 8080 " );

            URL u 
=   new  URL( " http://www.baidu.com " );
            HttpURLConnection conn 
=  (HttpURLConnection) u.openConnection();

            String authentication 
=   " dizh:dizhuang1984HIT* " ;
            String encodedLogin 
=   new  BASE64Encoder()
                .encodeBuffer(authentication.getBytes()).replaceAll(
" \n " "" );
            conn.setRequestProperty(
" Proxy-Authorization " " Basic  "
                
+  encodedLogin);
            conn.connect();

            
int  length  =  conn.getContentLength();
            System.out.println(length);
            InputStream is 
=  conn.getInputStream();
            
byte [] b  =   new   byte [ 4   *   1024 ];
            is.read(b);
            
for  ( int  i  =   0 ; i  <  b.length; i ++ ) {
                System.out.print((
char ) b[i]);
            }
        } 
catch  (IOException e) {
            e.printStackTrace();
        }

    }
}

这样,就可以访问baidu了,不过这段代码我抄别人,需要注意的是解析返回内容那里可能不是很对,这就是个demo版本的。

PS : 如果不加replaceAll方法,会出现:

java.lang.IllegalArgumentException: Illegal character(s) in message header value: Basic Y2FpeGlhbjI6OTYxOTEyNjQ=

at sun.net.www.protocol.http.HttpURLConnection.checkMessageHeader(HttpURLConnection.java:200)
at sun.net.www.protocol.http.HttpURLConnection.setRequestProperty(HttpURLConnection.java:1553)
at src.test.URLTest.main(URLTest.java:23)
Exception in thread "main"
上面提示的错误,按照网上人解释是:

“由于BASE64Encode会在字符多余76个(我也不知道为什么要是76个)的时候在数组尾部添加换行符“\n”,由于这个的原因导致了程序出错。” 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值