Java API代理示例
流程:调用 API → 解析 JSON → 处理错误 → 使用返回代理访问目标站。
提示
下述示例均采用 IP 白名单模式(无需用户名密码认证)。请使用合适的 JSON 解析库,生产环境可选 Jackson/Gson 等。
HttpClient 4.x
1import org.apache.http.HttpHost;2import org.apache.http.client.config.RequestConfig;3import org.apache.http.client.methods.CloseableHttpResponse;4import org.apache.http.client.methods.HttpGet;5import org.apache.http.impl.client.CloseableHttpClient;6import org.apache.http.impl.client.HttpClients;7import org.apache.http.util.EntityUtils;8import org.json.JSONArray;9import org.json.JSONObject;1011public class ApiProxyDemo {12static String apiUrl = "http://ip.16yun.cn:817/myip/pl/<ORDER_ID>/?s=<ORDER_SIGN>&u=<USER>&format=json";1314static String httpGet(String url) throws Exception {15try (CloseableHttpClient client = HttpClients.createDefault()) {16HttpGet get = new HttpGet(url);17try (CloseableHttpResponse resp = client.execute(get)) {18int code = resp.getStatusLine().getStatusCode();19if (code != 200) {20throw new RuntimeException("API错误: " + code);21}22return EntityUtils.toString(resp.getEntity(), "UTF-8");23}24}25}2627static void visitWithProxy(String ip, int port) throws Exception {28HttpHost proxy = new HttpHost(ip, port, "http");29RequestConfig cfg = RequestConfig.custom().setProxy(proxy).setConnectTimeout(10000).setSocketTimeout(10000).build();3031try (CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(cfg).build()) {32HttpGet get = new HttpGet("https://httpbin.org/ip");33try (CloseableHttpResponse resp = client.execute(get)) {34int code = resp.getStatusLine().getStatusCode();35if (code != 200) throw new RuntimeException("访问失败: " + code);36System.out.println(EntityUtils.toString(resp.getEntity(), "UTF-8"));37}38}39}4041public static void main(String[] args) throws Exception {42String body = httpGet(apiUrl);43JSONArray arr = new JSONArray(body);44if (arr.length() == 0) throw new RuntimeException("API 返回为空");45JSONObject first = arr.getJSONObject(0);46String ip = first.getString("ip");47int port = first.getInt("port");48visitWithProxy(ip, port);49}50}
OkHttp
1import okhttp3.*;2import org.json.JSONArray;3import org.json.JSONObject;45public class ApiProxyOkHttpDemo {6static String apiUrl = "http://ip.16yun.cn:817/myip/pl/<ORDER_ID>/?s=<ORDER_SIGN>&u=<USER>&format=json";78public static void main(String[] args) throws Exception {9OkHttpClient client = new OkHttpClient.Builder().build();10Request req = new Request.Builder().url(apiUrl).build();11Response r = client.newCall(req).execute();12if (!r.isSuccessful()) throw new RuntimeException("API错误: " + r.code());13JSONArray arr = new JSONArray(r.body().string());14if (arr.length() == 0) throw new RuntimeException("API 返回为空");15JSONObject first = arr.getJSONObject(0);16String ip = first.getString("ip");17int port = first.getInt("port");1819java.net.Proxy proxy = new java.net.Proxy(java.net.Proxy.Type.HTTP, new java.net.InetSocketAddress(ip, port));20OkHttpClient proxied = new OkHttpClient.Builder().proxy(proxy).build();21Request rr = new Request.Builder().url("https://httpbin.org/ip").build();22Response r2 = proxied.newCall(rr).execute();23if (!r2.isSuccessful()) throw new RuntimeException("访问失败:" + r2.code());24System.out.println(r2.body().string());25}26}
Jsoup
1import org.jsoup.Connection;2import org.jsoup.Jsoup;3import org.jsoup.nodes.Document;4import org.json.JSONArray;5import org.json.JSONObject;67public class ApiProxyJsoupDemo {8static String apiUrl = "http://ip.16yun.cn:817/myip/pl/<ORDER_ID>/?s=<ORDER_SIGN>&u=<USER>&format=json";910static JSONObject fetchFirstProxy() throws Exception {11Connection.Response res = Jsoup.connect(apiUrl)12.ignoreContentType(true)13.timeout(10_000)14.execute();15int code = res.statusCode();16if (code != 200) {17switch (code) {18case 400: throw new RuntimeException("API错误 400: 参数错误");19case 403: throw new RuntimeException("API错误 403: 主机IP不在白名单");20case 429: throw new RuntimeException("API错误 429: 提取频率过快");21default: throw new RuntimeException("API错误: " + code);22}23}24JSONArray arr = new JSONArray(res.body());25if (arr.length() == 0) throw new RuntimeException("API 返回为空");26return arr.getJSONObject(0);27}2829static void visitWithJsoup(String ip, int port) throws Exception {30Document doc = Jsoup.connect("https://httpbin.org/ip")31.proxy(ip, port)32.userAgent("Mozilla/5.0")33.timeout(10_000)34.get();35System.out.println(doc.body().text());36}3738public static void main(String[] args) throws Exception {39JSONObject first = fetchFirstProxy();40String ip = first.getString("ip");41int port = first.getInt("port");42visitWithJsoup(ip, port);43}44}
Selenium(Chrome 示例)
1import org.json.JSONArray;2import org.json.JSONObject;3import org.openqa.selenium.WebDriver;4import org.openqa.selenium.chrome.ChromeDriver;5import org.openqa.selenium.chrome.ChromeOptions;67import java.net.URI;8import java.net.http.HttpClient;9import java.net.http.HttpRequest;10import java.net.http.HttpResponse;11import java.time.Duration;1213public class ApiProxySeleniumDemo {14static String apiUrl = "http://ip.16yun.cn:817/myip/pl/<ORDER_ID>/?s=<ORDER_SIGN>&u=<USER>&format=json";1516static JSONObject fetchFirstProxy() throws Exception {17HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();18HttpRequest req = HttpRequest.newBuilder(URI.create(apiUrl)).timeout(Duration.ofSeconds(10)).GET().build();19HttpResponse<String> resp = client.send(req, HttpResponse.BodyHandlers.ofString());20int code = resp.statusCode();21if (code != 200) {22switch (code) {23case 400: throw new RuntimeException("API错误 400: 参数错误");24case 403: throw new RuntimeException("API错误 403: 主机IP不在白名单");25case 429: throw new RuntimeException("API错误 429: 提取频率过快");26default: throw new RuntimeException("API错误: " + code);27}28}29JSONArray arr = new JSONArray(resp.body());30if (arr.length() == 0) throw new RuntimeException("API 返回为空");31return arr.getJSONObject(0);32}3334public static void main(String[] args) throws Exception {35JSONObject first = fetchFirstProxy();36String ip = first.getString("ip");37int port = first.getInt("port");3839ChromeOptions options = new ChromeOptions();40options.addArguments("--proxy-server=http://" + ip + ":" + port);41WebDriver driver = new ChromeDriver(options);42try {43driver.get("https://httpbin.org/ip");44System.out.println(driver.getPageSource());45} finally {46driver.quit();47}48}49}
WebMagic
1import org.json.JSONArray;2import org.json.JSONObject;3import us.codecraft.webmagic.Page;4import us.codecraft.webmagic.Site;5import us.codecraft.webmagic.Spider;6import us.codecraft.webmagic.processor.PageProcessor;7import us.codecraft.webmagic.downloader.HttpClientDownloader;8import us.codecraft.webmagic.proxy.Proxy;9import us.codecraft.webmagic.proxy.SimpleProxyProvider;1011import java.net.URI;12import java.net.http.HttpClient;13import java.net.http.HttpRequest;14import java.net.http.HttpResponse;15import java.time.Duration;1617public class ApiProxyWebMagicDemo implements PageProcessor {18static String apiUrl = "http://ip.16yun.cn:817/myip/pl/<ORDER_ID>/?s=<ORDER_SIGN>&u=<USER>&format=json";1920private final Site site = Site.me().setRetryTimes(1).setTimeOut(10_000);2122static JSONObject fetchFirstProxy() throws Exception {23HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();24HttpRequest req = HttpRequest.newBuilder(URI.create(apiUrl)).timeout(Duration.ofSeconds(10)).GET().build();25HttpResponse<String> resp = client.send(req, HttpResponse.BodyHandlers.ofString());26int code = resp.statusCode();27if (code != 200) {28switch (code) {29case 400: throw new RuntimeException("API错误 400: 参数错误");30case 403: throw new RuntimeException("API错误 403: 主机IP不在白名单");31case 429: throw new RuntimeException("API错误 429: 提取频率过快");32default: throw new RuntimeException("API错误: " + code);33}34}35JSONArray arr = new JSONArray(resp.body());36if (arr.length() == 0) throw new RuntimeException("API 返回为空");37return arr.getJSONObject(0);38}3940@Override41public void process(Page page) {42System.out.println(page.getRawText());43}4445@Override46public Site getSite() {47return site;48}4950public static void main(String[] args) throws Exception {51JSONObject first = fetchFirstProxy();52String ip = first.getString("ip");53int port = first.getInt("port");5455HttpClientDownloader downloader = new HttpClientDownloader();56downloader.setProxyProvider(SimpleProxyProvider.from(new Proxy(ip, port)));5758Spider.create(new ApiProxyWebMagicDemo())59.setDownloader(downloader)60.addUrl("https://httpbin.org/ip")61.run();62}63}
crawler4j
1import org.json.JSONArray;2import org.json.JSONObject;34import edu.uci.ics.crawler4j.crawler.CrawlConfig;5import edu.uci.ics.crawler4j.crawler.CrawlController;6import edu.uci.ics.crawler4j.crawler.Page;7import edu.uci.ics.crawler4j.crawler.WebCrawler;8import edu.uci.ics.crawler4j.fetcher.PageFetcher;9import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;10import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;11import edu.uci.ics.crawler4j.url.WebURL;1213import java.net.URI;14import java.net.http.HttpClient;15import java.net.http.HttpRequest;16import java.net.http.HttpResponse;17import java.nio.charset.StandardCharsets;18import java.time.Duration;1920public class ApiProxyCrawler4jDemo {21static String apiUrl = "http://ip.16yun.cn:817/myip/pl/<ORDER_ID>/?s=<ORDER_SIGN>&u=<USER>&format=json";2223static JSONObject fetchFirstProxy() throws Exception {24HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();25HttpRequest req = HttpRequest.newBuilder(URI.create(apiUrl)).timeout(Duration.ofSeconds(10)).GET().build();26HttpResponse<String> resp = client.send(req, HttpResponse.BodyHandlers.ofString());27int code = resp.statusCode();28if (code != 200) {29switch (code) {30case 400: throw new RuntimeException("API错误 400: 参数错误");31case 403: throw new RuntimeException("API错误 403: 主机IP不在白名单");32case 429: throw new RuntimeException("API错误 429: 提取频率过快");33default: throw new RuntimeException("API错误: " + code);34}35}36JSONArray arr = new JSONArray(resp.body());37if (arr.length() == 0) throw new RuntimeException("API 返回为空");38return arr.getJSONObject(0);39}4041public static class SinglePageCrawler extends WebCrawler {42@Override43public boolean shouldVisit(Page referringPage, WebURL url) {44return true; // 仅示例45}4647@Override48public void visit(Page page) {49String content = new String(page.getContentData(), StandardCharsets.UTF_8);50System.out.println(content);51}52}5354public static void main(String[] args) throws Exception {55JSONObject first = fetchFirstProxy();56String ip = first.getString("ip");57int port = first.getInt("port");5859CrawlConfig config = new CrawlConfig();60config.setCrawlStorageFolder("./crawl_data");61config.setPolitenessDelay(200);62config.setMaxDepthOfCrawling(0);63config.setProxyHost(ip);64config.setProxyPort(port);6566PageFetcher pageFetcher = new PageFetcher(config);67RobotstxtConfig robotstxtConfig = new RobotstxtConfig();68RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);69CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer);7071controller.addSeed("https://httpbin.org/ip");72controller.start(SinglePageCrawler.class, 1);73}74}