首页 > 代码库 > Java通过代理服务器上网

Java通过代理服务器上网

完整代码

package com.proj.net;

//导入编码的jar文件
import it.sauronsoftware.base64.Base64;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


/**
 * 很多公司会对网上进行限制,要通过代理服务器和口令才能连接外网。<br>
 * 这种方式有很多好处:<br>
 * 1、安全,代理服务器像一层过滤层;<br>
 * 2、节省成本,只需要分配很少的IP地址即可;<br>
 * 3、对员工上网可以个性化配置,避免有人下载大量数据而造成网络拥堵不堪。<br>
 * 
 * 本文通过一个小案例来介绍如何在程序里跨过局域网访问外网。<br>
 * 对于搞网络开发的人来说,不值一提;但对于做JAVA EE应用开发的人来说,可以参考。<br>
 * 
 * @author 王一洋
 * 
 * 2014-10-30
 * */
public class Test {
	public static void main(String[] args) {
		try {
			//两种方式设置代理服务器
			//设置代理1
			//Proxy proxy = new Proxy(Proxy.Type.HTTP,new InetSocketAddress("", 80));
			//设置代理2
			System.getProperties().setProperty( "http.proxyHost", "");

			System.getProperties().setProperty( "http.proxyPort", "" );

			String urlString = "http://blog.csdn.net/";
			URL url = new URL(urlString);
			//对应第一种设置方式
			//HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(proxy);
			
			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
			urlConnection.setRequestMethod("GET");
			urlConnection.setConnectTimeout(1000);
			//设置User Agent
			urlConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
			//设置访问的用户名和密码
			urlConnection.setRequestProperty( "Proxy-Authorization", "Basic" + Base64.encode("username:password") );
			urlConnection.connect();
			System.out.print(urlConnection.getResponseCode());
			BufferedInputStream bis = new BufferedInputStream(urlConnection.getInputStream());
			InputStreamReader isr = new InputStreamReader(bis,"UTF-8");
			BufferedReader bufferedReader = new BufferedReader(isr);
			String str = "";
			StringBuffer buffer = new StringBuffer("");
			while((str = bufferedReader.readLine())!=null){
				buffer.append(str+"\r\n");
			}
			System.out.println(buffer);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


返回code:200,OK!


异常Server returned HTTP response code: 403 for URL

在url.openConnection()后添加:

connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");


Java通过代理服务器上网