Java通過(guò)代理服務(wù)器上網(wǎng)
來(lái)源:程序員人生 發(fā)布時(shí)間:2014-11-09 10:17:26 閱讀次數(shù):2484次
完全代碼
package com.proj.net;
//導(dǎo)入編碼的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;
/**
* 很多公司會(huì)對(duì)網(wǎng)上進(jìn)行限制,要通過(guò)代理http://www.jyygyx.com/server/和口令才能連接外網(wǎng)。<br>
* 這類(lèi)方式有很多好處:<br>
* 1、安全,代理http://www.jyygyx.com/server/像1層過(guò)濾層;<br>
* 2、節(jié)省本錢(qián),只需要分配很少的IP地址便可;<br>
* 3、對(duì)員工上網(wǎng)可以個(gè)性化配置,避免有人下載大量數(shù)據(jù)而造成網(wǎng)絡(luò)擁堵不堪。<br>
*
* 本文通過(guò)1個(gè)小案例來(lái)介紹如何在程序里跨過(guò)局域網(wǎng)訪問(wèn)外網(wǎng)。<br>
* 對(duì)弄網(wǎng)絡(luò)開(kāi)發(fā)的人來(lái)講,不值1提;但對(duì)做JAVA EE利用開(kāi)發(fā)的人來(lái)講,可以參考。<br>
*
* @author 王1洋
*
* 2014⑴0⑶0
* */
public class Test {
public static void main(String[] args) {
try {
//兩種方式設(shè)置代理http://www.jyygyx.com/server/
//設(shè)置代理1
//Proxy proxy = new Proxy(Proxy.Type.HTTP,new InetSocketAddress("", 80));
//設(shè)置代理2
System.getProperties().setProperty( "http.proxyHost", "");
System.getProperties().setProperty( "http.proxyPort", "" );
String urlString = "http://blog.csdn.net/";
URL url = new URL(urlString);
//對(duì)應(yīng)第1種設(shè)置方式
//HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(proxy);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setConnectTimeout(1000);
//設(shè)置User Agent
urlConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//設(shè)置訪問(wèn)的用戶(hù)名和密碼
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)");
生活不易,碼農(nóng)辛苦
如果您覺(jué)得本網(wǎng)站對(duì)您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈(zèng)