Java通过代理server上网

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;

/**

* 非常多公司会对网上进行限制,要通过代理server和口令才干连接外网。

<br>

* 这样的方式有非常多优点:<br>

* 1、安全。代理server像一层过滤层;<br>

* 2、节省成本,仅仅须要分配非常少的IP地址就可以;<br>

* 3、对员工上网能够个性化配置,避免有人下载大量数据而造成网络拥堵不堪。<br>

*

* 本文通过一个小案例来介绍怎样在程序里跨过局域网訪问外网。

<br>

* 对于搞网络开发的人来说。不值一提;但对于做JAVA EE应用开发的人来说,能够參考。<br>

*

* @author 王一洋

*

* 2014-10-30

* */

public class Test {

public static void main(String[] args) {

try {

//两种方式设置代理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);

//相应第一种设置方式

//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)");

//设置訪问的username与password

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通过代理server上网 的全部内容, 来源链接: utcz.com/z/389800.html

回到顶部