關鍵是設置系統屬性
java
System.setProperty("http.proxySet", "true"); System.setProperty("http.proxyHost", proxy[0]); System.setProperty("http.proxyPort", proxy[1]);
直接上代碼app
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.regex.Matcher; import java.util.regex.Pattern; public class HttpProxy { private static String[] proxyArray = { "120.52.72.48:80", "110.52.232.60:80", "117.135.251.133:80", "122.140.245.106:8000", "119.255.9.93:80", "117.135.252.227:80", "120.198.231.22:8080", "117.158.149.34:80", "183.239.167.122:8080" }; public static void main(String[] args) throws Exception { final String spec = "http://1212.ip138.com/ic.asp"; final String charset = "GB2312"; System.out.println("不使用代理"); parse(sendHttpPost(spec, charset)); for (int i = 0; i < proxyArray.length; i++) { try { String[] proxy = proxyArray[i].split(":"); System.setProperty("http.proxySet", "true"); System.setProperty("http.proxyHost", proxy[0]); System.setProperty("http.proxyPort", proxy[1]); System.out.println("代理IP是: " + proxyArray[i]); parse(sendHttpPost(spec, charset)); } catch (Throwable t) { System.out.println(t); } } } private static void parse(String result) { Pattern pattern = Pattern.compile("<center>(.*)</center>"); Matcher matcher = pattern.matcher(result); while (matcher.find()) { System.out.println(matcher.group(1)); } System.out.println(); } private static String sendHttpPost(String spec, String charset) throws MalformedURLException, IOException { URL url = new URL(spec); URLConnection connection = url.openConnection(); HttpURLConnection httpURLConnection = (HttpURLConnection) connection; StringBuffer resultBuffer = new StringBuffer(); if (httpURLConnection.getResponseCode() == 200) { try (BufferedReader reader = new BufferedReader( new InputStreamReader(httpURLConnection.getInputStream(), charset))) { String tempLine = null; while ((tempLine = reader.readLine()) != null) { resultBuffer.append(tempLine); } } } return resultBuffer.toString(); } }
輸出ide
不使用代理 您的IP是:[183.15.246.30] 來自:廣東省深圳市 電信 代理IP是: 120.52.72.48:80 您的IP是:[221.221.163.195] 來自:北京市北京市 聯通 代理IP是: 110.52.232.60:80 您的IP是:[183.15.246.30] 來自:廣東省深圳市 電信 代理IP是: 117.135.251.133:80 您的IP是:[117.135.251.133] 來自:貴州省 移動 代理IP是: 122.140.245.106:8000 您的IP是:[183.15.246.30] 來自:廣東省深圳市 電信 代理IP是: 119.255.9.93:80 您的IP是:[183.15.246.30] 來自:廣東省深圳市 電信 代理IP是: 117.135.252.227:80 您的IP是:[117.135.252.227] 來自:貴州省 移動 代理IP是: 120.198.231.22:8080 您的IP是:[120.198.231.22] 來自:廣東省東莞市 移動 代理IP是: 117.158.149.34:80 您的IP是:[183.15.246.30] 來自:廣東省深圳市 電信 代理IP是: 183.239.167.122:8080 您的IP是:[183.239.167.122] 來自:廣東省深圳市 移動