ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

Java实现两个Ip相互跳转

2026/8/9 5:13:25 拓冰建站 浏览量
Java实现两个Ip相互跳转

需求:在请求HttpClient时,如果访问的http://127.0.0.1:5004/proxy/1为空或者为html(看自己的需求而定),那么就跳转到http://192.128.121.140:5004/proxy/1

传入的ip1和ip2分别是127.0.0.1和192.128.121.140

private String sendRequest(String ip1, String ip2) {CloseableHttpClient httpClient = HttpClients.createDefault();String urlTemplate = "http://%s/proxy/1";String resBody = sendRequestToIP(httpClient, String.format(urlTemplate, ip1));if (resBody.contains("html") || resBody.isEmpty()) {resBody = sendRequestToIP(httpClient, String.format(urlTemplate, ip2));}return resBody;
}
private String sendRequestToIP(CloseableHttpClient httpClient, String url) {String resBody = "";try {HttpGet request = new HttpGet(url);CloseableHttpResponse response = httpClient.execute(request);resBody = EntityUtils.toString(response.getEntity());} catch (Exception e) {log.error("Exception occurred while sending request to " + url);}return resBody;
}