【轉】JAVA 驗證代理是否可用
苦苦在網上找了一天,先後試了四種方法,最終實現,在此做一總結
方法一:
HttpClient 方法
HttpClient client=new HttpClient();
client.getHostConfiguration().setHost("111432.1.32.93", 80, "http");
HttpMethod method =new GetMethod("http://www.07073.com/gld/");
int statusCode = client.executeMethod(method);
System.out.println("---------"+statusCode+"------------");
方法二:
JAVA設定JVM代理方法
System.getProperty("proxySet", "true");
System.getProperties().setProperty("http.proxyHost", "1532603.11.62.176");
System.getProperties().setProperty("http.proxyPort", "810");
System.out.println(getHtml("http://www.07073.com/gld/"));
private String getHtml(String address){
StringBuffer html = new StringBuffer();
String result = null;
URL url;
try {
url = new URL(address);
URLConnection conn = url.openConnection();
conn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; GTB5; .NET CLR 2.0.50727; CIBA)");
BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
try {
String inputLine;
byte[] buf = new byte[4096];
int bytesRead = 0;
while (bytesRead >= 0) {
inputLine = new String(buf, 0, bytesRead, "ISO-8859-1");
html.append(inputLine);
bytesRead = in.read(buf);
inputLine = null;
}
buf = null;
} finally {
in.close();
conn = null;
url = null;
}
result = new String(html.toString().trim().getBytes("ISO-8859-1"), "gb2312").toLowerCase();
} catch (Exception e) {
e.printStackTrace();
return null;
}
html=null;
return result;
}
方法三:
JAVA PING網址方法
Process p = Runtime.getRuntime().exec("ping "+ip);
InputStream is = p.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
String time=null;
String temp=null;
while ((line = reader.readLine()) != null) {
temp+=line;
//判斷是否丟包
if(line.indexOf("out")>0){
flag=false;
break;
}
//取得延時
if(line.indexOf("time")>0&&line.indexOf("ms")>0){
time=line.substring(line.indexOf("time")+5,line.indexOf("ms"));
System.out.println(line.substring(line.indexOf("time")+5,line.indexOf("ms")));
//如果延時小於5秒
if(Integer.valueOf(time)<5000)
flag=true;
else
flag=false;
break;
}
}
System.out.println(temp);
is.close();
reader.close();
p.destroy();
System.out.println(getHtml("http://www.07073.com/gld/"));
method.eleaseConnection();
方法四:
//Proxy類代理方法
URL url = new URL("http://www.baidu.com");
// 建立代理伺服器
InetSocketAddress addr=null;
addr=new InetSocketAddress("61.135.149.177",8888);
Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); // http 代理
URLConnection conn = url.openConnection(proxy);
InputStream in = conn.getInputStream();
String s = IOUtils.toString(in);
//System.out.println(s);
if(s.indexOf("百度")>0){
System.out.println("ok");
}
前二種方法都會因代理不好用,而程式自動採用本機IP訪問頁面,所以也驗證不出代理是否可用,而第三種方法也只能測試代理的速度,也沒有實際效用,第四種方法對於設定代理後無法訪問頁面,得不到頁面流時會報錯,可採用