How to geolocate an IP address in Java
2 min readJan 20, 2020
IP location has useful applications ranging anywhere from gaining user data to filtering out phishing scams. Whatever your purpose might be, setting up geolocation will take about 5 minutes, so let’s get straight to it.
First we must enter references in Maven POM so that Jitpack can dynamically compile our library. Easy enough:
Repository
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
Dependency
<dependencies>
<dependency>
<groupId>com.github.Cloudmersive</groupId>
<artifactId>Cloudmersive.APIClient.Java</artifactId>
<version>v2.75</version>
</dependency>
</dependencies>
And with that out of the way, call iPAddressPost with the following code, and we’re done!
// Import classes://import com.cloudmersive.client.invoker.ApiClient;//import com.cloudmersive.client.invoker.ApiException;//import com.cloudmersive.client.invoker.Configuration;//import com.cloudmersive.client.invoker.auth.*;//import com.cloudmersive.client.IpAddressApi;ApiClient defaultClient = Configuration.getDefaultApiClient();// Configure API key authorization: ApikeyApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");Apikey.setApiKey("YOUR API KEY");// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)//Apikey.setApiKeyPrefix("Token");IpAddressApi apiInstance = new IpAddressApi();String value = "value_example"; // String | IP address to geolocate, e.g. \"55.55.55.55\". The input is a string so be sure to enclose it in double-quotes.try {GeolocateResponse result = apiInstance.iPAddressPost(value);System.out.println(result);} catch (ApiException e) {System.err.println("Exception when calling IpAddressApi#iPAddressPost");e.printStackTrace();}
Seriously, it’s just that easy. Here’s an example response for 1.160.10.240 so that you can see the format:
{
"CountryCode": "TW",
"CountryName": "Taiwan",
"City": "Taipei",
"RegionCode": "TPE",
"RegionName": "Taipei City",
"ZipCode": "",
"TimezoneStandardName": "Asia/Taipei",
"Latitude": 25.0478,
"Longitude": 121.5318
}