我这里提供2个方法都可以实现:第一个是createIPAddress()和convertStreamToString()
import java.io.IOException; import java.io.InputStream; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.URL; import java.net.URLConnection; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.io.BufferedReader; import java.io.InputStreamReader; /** * 批量代理IP有效检测 * * @param IP * @param post */ public static void createIPAddress(String ip,int port) { URL url = null; try { url = new URL("http://www.baidu.com"); } catch (MalformedURLException e) { System.out.println("url invalidate"); } InetSocketAddress addr = null; addr = new InetSocketAddress(ip, port); Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); // http proxy InputStream in = null; try { URLConnection conn = url.openConnection(proxy); conn.setConnectTimeout(1000); in = conn.getInputStream(); } catch (Exception e) { System.out.println("ip " + ip + " is not aviable");//异常IP } String s = convertStreamToString(in); System.out.println(s); // System.out.println(s); if (s.indexOf("baidu") > 0) {//有效IP System.out.println(ip + ":"+port+ " is ok"); } } public static String convertStreamToString(InputStream is) { if (is == null) return ""; BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "/n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); }
第二个方法是checkProxyIp()
/** * 批量代理IP有效检测 * * @param proxyIpMap * @param reqUrl */ public static void checkProxyIp(Map<String, Integer> proxyIpMap, String reqUrl) { for (String proxyHost : proxyIpMap.keySet()) { Integer proxyPort = proxyIpMap.get(proxyHost); int statusCode = 0; try { HttpClient httpClient = new HttpClient(); httpClient.getHostConfiguration().setProxy(proxyHost, proxyPort); // 连接超时时间(默认10秒 10000ms) 单位毫秒(ms) int connectionTimeout = 10000; // 读取数据超时时间(默认30秒 30000ms) 单位毫秒(ms) int soTimeout = 30000; httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout); httpClient.getHttpConnectionManager().getParams().setSoTimeout(soTimeout); HttpMethod method = new GetMethod(reqUrl); statusCode = httpClient.executeMethod(method); } catch (Exception e) { System.out.println("ip " + proxyHost + " is not aviable"); } if(statusCode>0){ System.out.format("%s:%s-->%sn", proxyHost, proxyPort,statusCode); } } }
时间: 2024-10-19 08:41:57