400-692-3698

帮助文档

七大主流语言SDK及示例

可复制供用户参考
      当前位置: 首页 > SDK 示例

如何在JAVA中使用代理示例

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;

public class ProxyRequest {

    public static void main(String[] args) {
        String api = ""; // 这里填写你购买后生成的API网址,如果没有或者不会,请找客服  如:http://www.soyunip.com/api?ddbh=s8349453653

        try {
            URL apiUrl = new URL(api);
            HttpURLConnectiion apiConnection = (HttpURLConnection) apiUrl.openConnection();
            apiConnection.setRequestMethod("GET");
            apiConnection.setConnectTimeout(10000); // 超时设置为10秒

            int responseCode = apiConnection.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                throw new RuntimeException("Failed to get IP address: HTTP error code : " + responseCode);
            }

            BufferedReader in = new BufferedReader(new InputStreamReader(apiConnection.getInputStream()));
            String inputLine;
            StringBuilder content = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine).append("\n");
            }
            in.close();

            String ip = content.toString().trim(); // 返回的内容如:125.26.21.154:13456

            // 如果返回是多行多个代理信息的,需要解析一下
            String[] ips = ip.split("\r\n"); // 这里返回多行多个代理IP,默认是以\r\n分隔符的

            if (ips.length == 0 || ips[0].isEmpty()) {
                throw new RuntimeException("No valid IP address found in response");
            }

            String myip = ips[0]; // 这里取第一个代理IP 实际应用时,根据需要自己选择

            // 代理服务器
            String ipport = "http://" + myip;

            // 下面举例是你要访问的网站链接
            String url = "http://myip.ipip.net";

            URL targetUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) targetUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Proxy-Host", myip.split(":")[0]);
            connection.setRequestProperty("Proxy-Port", myip.split(":")[1]);

            responseCode = connection.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                throw new RuntimeException("Failed to fetch data from target site: HTTP error code : " + responseCode);
            }

            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            content = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine).append("\n");
            }
            in.close();

            System.out.println(content.toString()); // 打印返回的内容

        } catch (Exception e) {
            System.err.println("An error occurred: " + e.getMessage());
        }
    }
}
654888147
在线时间
8:00-24:00
扫码加客服微信
400-692-3698
反馈类型
反馈内容
联系人姓名
联系电话