複製代碼代碼如下:
包裝測試;
導入java.io..bufferedreader;
導入java.io.ioexception;
導入java.io.inputstream;
導入java.io.io.inputStreamReader;
導入java.net.authenticator;
導入java.net.httpurlConnection;
導入java.net.passwordauthentication;
導入java.net.url;
導入java.net.urlconnection;
導入java.util.properties;
公共類urltest {
//公共方法,返回字符串,錯誤則返回,“錯誤打開URL”
公共靜態字符串getContent(string strurl){
嘗試 {
URL URL =新URL(strurl);
BufferedReader br = new BufferedReader(new InputStreamReader(url)
.opstream()));
字符串s =“”;
StringBuffer SB = new StringBuffer(“”);
while((s = br.readline())!= null){
sb.append(s +“/r/n”);
}
br.close();
返回sb.tostring();
} catch(異常E){
返回“錯誤打開URL:” + strurl;
}
}
public static void initproxy(字符串主機,int端口,最終字符串用戶名,
最終字符串密碼){
authenticator.setDefault(new AuthenTicator(){
受保護的密碼授權getPasswordauthentication(){
返回新的passwordAuthentication(用戶名,
new String(password).toCharArray());
}
});
system.setProperty(“ http.proxytype”,“ 4”);
system.setProperty(“ http.proxyport”,integer.tostring(port));
system.setProperty(“ http.proxyhost”,主機);
system.setProperty(“ http.proxyset”,“ true”);
}
公共靜態void main(string [] args)拋出ioexception {
字符串url =“ //www.vevb.com”;
字符串代理=“ http://192.168.22.81”;
int port = 80;
字符串用戶名=“用戶名”;
字符串密碼=“密碼”;
字符串curline =“”;
字符串content =“”;
URL Server = new URL(url);
initproxy(代理,端口,用戶名,密碼);
httpurlconnection connection =(httpurlConnection)服務器
.opennnection();
Connect.connect();
InputStream is = Connection.getInputStream();
BufferedReader Reader =新的BufferedReader(新
InputStreamReader(IS));
while(((curline = reader.readline())!= null){
content = content + curline +“/r/n”;
}
system.out.println(“ content =” + content);
is.close();
system.out.println(getContent(url));
}
}