import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.Map;
public class ApiIndexer {
/**
* Indexes content from API endpoints with optional flags.
* @param baseUrl The base URL of the API.
* @param flags A map of flags to values.
* @return A map containing the indexed data. Returns an empty map on error.
*/
public static Map<String, String> indexApiContent(String baseUrl, Map<String, String> flags) {
Map<String, String> indexedData = new HashMap<>();
try {
URI uri = new URI(baseUrl);
HttpRequest request = buildRequest(uri, flags);
HttpClient client = HttpClient.newHttpClient();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 200) {
System.err.println("API request failed with status code: " + response.statusCode());
return indexedData; // Return empty map on error
}
String content = response.body();
indexedData.put("content", content);
} catch (IOException | Exception e) {
System.err.println("An error occurred: " + e.getMessage());
return indexedData; // Return empty map on error
}
return indexedData;
}
/**
* Builds the HTTP request with optional flags.
* @param uri The URI of the API endpoint.
* @param flags A map of flags to values.
* @return The HttpRequest object.
*/
private static HttpRequest buildRequest(URI uri, Map<String, String> flags) throws Exception {
StringBuilder sb = new StringBuilder(uri.toString());
// Add query parameters
if (flags != null && !flags.isEmpty()) {
String queryParams = buildQueryParams(flags);
sb.append("?").append(queryParams);
}
return HttpRequest.newBuilder()
.uri(URI.create(sb.toString()))
.build();
}
/**
* Builds the query parameters string.
* @param flags A map of flags to values.
* @return The query parameters string.
*/
private static String buildQueryParams(Map<String, String> flags) {
StringBuilder queryParams = new StringBuilder();
for (Map.Entry<String, String> entry : flags.entrySet()) {
queryParams.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
}
// Remove trailing &
if (queryParams.length() > 0) {
queryParams.deleteCharAt(queryParams.length() - 1);
}
return queryParams.toString();
}
public static void main(String[] args) {
// Example usage
String baseUrl = "https://jsonplaceholder.typicode.com/todos";
Map<String, String> flags = new HashMap<>();
flags.put("limit", "10"); // Example flag
flags.put("offset", "20");
Map<String, String> indexedData = indexApiContent(baseUrl, flags);
if (!indexedData.isEmpty()) {
System.out.println("Indexed data:");
System.out.println(indexedData);
}
}
}
Add your comment