复制代码代码如下:
包装测试;
导入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));
}
}