需求:在请求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
java
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;
}
java
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;
}