程序员人生 网站导航

Java通过代理服务器上网

栏目:互联网时间:2014-11-09 10:17:26

完全代码

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; /** * 很多公司会对网上进行限制,要通过代理http://www.wfuyu.com/server/和口令才能连接外网。<br> * 这类方式有很多好处:<br> * 1、安全,代理http://www.wfuyu.com/server/像1层过滤层;<br> * 2、节省本钱,只需要分配很少的IP地址便可;<br> * 3、对员工上网可以个性化配置,避免有人下载大量数据而造成网络拥堵不堪。<br> * * 本文通过1个小案例来介绍如何在程序里跨过局域网访问外网。<br> * 对弄网络开发的人来讲,不值1提;但对做JAVA EE利用开发的人来讲,可以参考。<br> * * @author 王1洋 * * 2014⑴0⑶0 * */ public class Test { public static void main(String[] args) { try { //两种方式设置代理http://www.wfuyu.com/server/ //设置代理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); //对应第1种设置方式 //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⑻"); BufferedReader bufferedReader = new BufferedReader(isr); String str = ""; StringBuffer buffer = new StringBuffer(""); while((str = bufferedReader.readLine())!=null){ buffer.append(str+" "); } 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)");


------分隔线----------------------------
------分隔线----------------------------

最新技术推荐