直接上代码:
- 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 的接口, 通过访问这个接口就可以看到效果了.
来源: http://www.bubuko.com/infodetail-2737620.html