Java实现两个Ip相互跳转

发布时间:2024年01月24日

需求:在请求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;
}
文章来源:https://blog.csdn.net/qq_46548855/article/details/135814709
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。