Welcome 微信登录

首页 / 操作系统 / Linux / Java通过代理服务器访问外部网络

今天闲来无事,看同事在做IIS监控内容,我想咱也没事看看HTTP什么的,在网上看,觉得Apache的httpclient开源包不错,封装了很多http操作,但目前我还没有仔细研究,只是用简单的socket连接,于是在网上搜罗代码,发现有两种方式可以进行访问,不过第二种目前我没有调试成功,第一种没有问题,因为我就是用公司的代理服务器上网的。代码如下: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(" ", "");
            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个)的时候在数组尾部添加换行符“ ”,由于这个的原因导致了程序出错。”