Skip to content

Instantly share code, notes, and snippets.

@DrMetallius
Created August 31, 2019 20:31
Show Gist options
  • Save DrMetallius/7e0e9bb82c9991900cfd3166f758dd47 to your computer and use it in GitHub Desktop.
Save DrMetallius/7e0e9bb82c9991900cfd3166f758dd47 to your computer and use it in GitHub Desktop.
Ipify API Helper
package com.acronis.ipifydemo;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
public class IpifyApiHelper {
private static final String HOST = "https://api.ipify.org";
private static final String ENCODING = "UTF-8";
private static final String TAG = IpifyApiHelper.class.getSimpleName();
public static String loadIpAddress() {
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) new URL(HOST).openConnection();
int response = conn.getResponseCode();
if (response != HttpURLConnection.HTTP_OK) return null;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.forName(ENCODING)));
try {
return reader.readLine();
} finally {
reader.close();
}
} catch (IOException e) {
Log.e(TAG, "Couldn't load the IP address", e);
return null;
} finally {
if (conn != null) conn.disconnect();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment