原文地址:http://www.cnblogs.com/junrong624/p/5416503.html
1 import java.io.IOException; 2 import java.io.InputStream; 3 import java.net.InetSocketAddress; 4 import java.net.Proxy; 5 import java.net.URL; 6 import java.net.URLConnection; 7 import java.nio.charset.Charset; 8 import java.util.HashMap; 9 import java.util.Iterator; 10 import java.util.Map; 11 import java.io.BufferedReader; 12 import java.io.InputStreamReader; 13 /**<br> * 批量代理IP有效检测<br> *<br> * @param IP<br> * @param post<br> */ 14 public static void createIPAddress(String ip,int port) { 15 URL url = null; 16 try { 17 url = new URL("http://www.baidu.com"); 18 } catch (MalformedURLException e) { 19 System.out.println("url invalidate"); 20 } 21 InetSocketAddress addr = null; 22 addr = new InetSocketAddress(ip, port); 23 Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); // http proxy 24 InputStream in = null; 25 try { 26 URLConnection conn = url.openConnection(proxy); 27 conn.setConnectTimeout(1000); 28 in = conn.getInputStream(); 29 } catch (Exception e) { 30 System.out.println("ip " + ip + " is not aviable");//异常IP 31 } 32 String s = convertStreamToString(in); 33 System.out.println(s); 34 // System.out.println(s); 35 if (s.indexOf("baidu") > 0) {//有效IP 36 System.out.println(ip + ":"+port+ " is ok"); 37 } 38 } 39 40 41 public static String convertStreamToString(InputStream is) { 42 if (is == null) 43 return ""; 44 BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 45 StringBuilder sb = new StringBuilder(); 46 String line = null; 47 try { 48 while ((line = reader.readLine()) != null) { 49 sb.append(line + "/n"); 50 } 51 } catch (IOException e) { 52 e.printStackTrace(); 53 } finally { 54 try { 55 is.close(); 56 } catch (IOException e) { 57 e.printStackTrace(); 58 } 59 } 60 return sb.toString(); 61 62 } 63
1 /** 2 * 批量代理IP有效检测 3 * 4 * @param proxyIpMap 5 * @param reqUrl 6 */ 7 public static void checkProxyIp(Map<String, Integer> proxyIpMap, String reqUrl) { 8 9 for (String proxyHost : proxyIpMap.keySet()) { 10 Integer proxyPort = proxyIpMap.get(proxyHost); 11 12 int statusCode = 0; 13 try { 14 HttpClient httpClient = new HttpClient(); 15 httpClient.getHostConfiguration().setProxy(proxyHost, proxyPort); 16 17 // 连接超时时间(默认10秒 10000ms) 单位毫秒(ms) 18 int connectionTimeout = 10000; 19 // 读取数据超时时间(默认30秒 30000ms) 单位毫秒(ms) 20 int soTimeout = 30000; 21 httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout); 22 httpClient.getHttpConnectionManager().getParams().setSoTimeout(soTimeout); 23 24 HttpMethod method = new GetMethod(reqUrl); 25 26 statusCode = httpClient.executeMethod(method); 27 } catch (Exception e) { 28 System.out.println("ip " + proxyHost + " is not aviable"); 29 } 30 if(statusCode>0){ 31 System.out.format("%s:%s-->%sn", proxyHost, proxyPort,statusCode); 32 } 33 34 } 35 }