Make sure the "responseCode" is "200-OK", before trying to get the InputStream in "UriBuilder.getPublicIP()".

This commit is contained in:
Lampros Smyrnaios 2023-01-11 16:02:31 +02:00
parent fd62ac567e
commit d96d0c68cd
1 changed files with 10 additions and 3 deletions

View File

@ -56,23 +56,30 @@ public class UriBuilder {
{
String publicIpAddress = "";
HttpURLConnection conn = null;
String urlString = "https://api.ipify.org/";
try {
conn = (HttpURLConnection) new URL("https://api.ipify.org/").openConnection();
conn = (HttpURLConnection) new URL(urlString).openConnection();
conn.setConnectTimeout(60_000);
conn.setReadTimeout(60_000);
conn.setRequestMethod("GET");
conn.connect();
int responseCode = conn.getResponseCode();
if ( responseCode != 200 ) {
logger.warn("Cannot get the publicIP address for this machine, as \"" + urlString + "\" returned the HTTP-error-code: " + responseCode);
return null;
}
try ( BufferedReader bf = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
publicIpAddress = bf.readLine().trim();
}
} catch (Exception e) {
logger.warn("Cannot get the publicIP address for this machine!", e);
logger.warn("Cannot get the publicIP address for this machine, from \"" + urlString + "\"!", e);
return null;
} finally {
if ( conn != null )
conn.disconnect();
}
return publicIpAddress;
}