To determine the usage type of an IP address using IP2Location.io in Java, you can use the IP2Location.io API to retrieve geolocation and related data. The usage type field specifies how the IP is being used. For usage types supported, please see API documentation for more info.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.CompletableFuture;
import com.google.gson.*;
public class Main {
public Main() {}
public static void main(String[] args) {
try {
String MyKey = "YOUR_API_KEY";
String MyIP = "8.8.8.8";
String url = "https://api.ip2location.io?format=json&key=" + MyKey + "&ip=" + MyIP;
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI(url))
.GET()
.build();
HttpClient client = HttpClient.newHttpClient();
CompletableFuture < HttpResponse < String >> response = client.sendAsync(request, HttpResponse.BodyHandlers.ofString());
int statusCode = response.thenApply(HttpResponse::statusCode).get();
if (statusCode == 200) {
String rawJSON = response.thenApply(HttpResponse::body).get();
JsonObject MyObj = JsonParser.parseString(rawJSON).getAsJsonObject();
if (MyObj.has("usage_type")) {
System.out.println("The usage type for IP " + MyIP + " is " + MyObj.get("usage_type").getAsString() + ".");
} else {
System.out.println("ERROR: The usage_type field requires a paid subscription to the Starter plan or higher.");
}
} else if (statusCode == 400 || statusCode == 401) {
String rawJSON = response.thenApply(HttpResponse::body).get();
if (rawJSON.contains("error_message")) {
throw new Exception("ERROR: " + JsonParser.parseString(rawJSON).getAsJsonObject().getAsJsonObject("error").get("error_message").getAsString());
}
throw new Exception(rawJSON);
} else {
String err = response.thenApply(HttpResponse::body).get();
throw new Exception(err);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
javac -classpath gson-2.11.0.jar Main.java
java -cp gson-2.11.0.jar; Main
This script will output the usage type of specified IP address. Make sure to replace 8.8.8.8 with the IP address you want and replace YOUR_API_KEY to your own API key.
Empower your applications with accurate IP geolocation information now.
Try It for Free