Java Code Example
A quick Java snippet to integrate into the FraudGuard.io API and associated explanation.
This Java code performs the following steps:
- Sets the FraudGuard.io API credentials (username and password).
- Defines the IP address to query.
- Constructs the API endpoint URL.
- Creates a URL object using the API URL.
- Opens a connection to the URL using HttpURLConnection.
- Sets the request method to GET.
- Sets the basic authentication header using Base64 encoding.
- Reads the response from the API.
- Prints the response.
- Closes the connection.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
public class FraudGuardAPIClient {
public static void main(String[] args) {
// FraudGuard.io API credentials
String username = "username";
String password = "password";
// IP address to query
String ipAddress = "8.8.8.8";
// API endpoint
String apiUrl = "https://api.fraudguard.io/ip/" + ipAddress;
try {
// Create URL object
URL url = new URL(apiUrl);
// Create HttpURLConnection object
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Set request method
connection.setRequestMethod("GET");
// Set basic authentication header
String authString = username + ":" + password;
String encodedAuthString = Base64.getEncoder().encodeToString(authString.getBytes());
String authHeaderValue = "Basic " + encodedAuthString;
connection.setRequestProperty("Authorization", authHeaderValue);
// Read response
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// Print response
System.out.println(response.toString());
// Close connection
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Make sure to replace ‘username’ and ‘password’ with your actual API credentials.