java使用代理模拟http get请求
直接上代码:
import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.URL; import java.net.URLConnection; public class Trans { static int timeout = 10 * 1000;// 以秒为单位 static String host = "117.177.243.6";//117.177.243.7 static int port = 80; /** * 主入口方法 * @param args */ public static void main(String[] args) { String url = "http://2018.ip138.com/ic.asp"; String result = get(url); System.out.println(result); } /** * 向指定URL发送GET方法的请求 */ public static String get(String url) { String result = ""; BufferedReader in = null; try { URL realUrl = new URL(url); // 创建代理服务器 InetSocketAddress addr = new InetSocketAddress(host, port); Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); //http 代理 // 打开和URL之间的连接 URLConnection connection = realUrl.openConnection(proxy); // 设置通用的请求属性 connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded;"); connection.setConnectTimeout(timeout); connection.setReadTimeout(timeout); // 建立实际的连接 connection.connect(); // 定义 BufferedReader输入流来读取URL的响应 in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "gbk")); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { e.printStackTrace(); } finally { try { if (in != null) { in.close(); } } catch (Exception e) { e.printStackTrace(); } } return result; } }
上面的IP:117.177.243.6和117.177.243.7是我在网上临时找的两个国内代理IP,你也可以自己找。
这个地址:http://2018.ip138.com/ic.asp是国内的一个获取客户端IP的接口,通过访问这个接口就可以看到效果了。