66 lines
2.7 KiB
Java
66 lines
2.7 KiB
Java
package tech.nevets.wikipediabot;
|
|
|
|
import com.google.gson.Gson;
|
|
import com.google.gson.JsonArray;
|
|
import com.google.gson.JsonElement;
|
|
import com.google.gson.JsonObject;
|
|
|
|
import java.io.IOException;
|
|
import java.net.URI;
|
|
import java.net.URLEncoder;
|
|
import java.net.http.HttpClient;
|
|
import java.net.http.HttpHeaders;
|
|
import java.net.http.HttpRequest;
|
|
import java.net.http.HttpResponse;
|
|
import java.nio.charset.StandardCharsets;
|
|
|
|
public class WikipediaRequest {
|
|
private static final Gson GSON = new Gson();
|
|
|
|
public static String wikipediaRequest(String topic) {
|
|
String topicProper = topic.replaceAll(" ", "_");
|
|
String strRes = wikiApiCall("https://en.wikipedia.org/api/rest_v1/page/summary/" + topicProper);
|
|
|
|
JsonObject res = GSON.fromJson(strRes, JsonObject.class);
|
|
if (res.get("title").getAsString().equals("Not found.")) {
|
|
JsonArray altRes = GSON.fromJson(wikiApiCall("https://en.wikipedia.org/w/api.php?action=opensearch&search=" + URLEncoder.encode(topic, StandardCharsets.UTF_8) + "&namespace=0&format=json"), JsonArray.class);
|
|
JsonArray similarList = altRes.get(1).getAsJsonArray();
|
|
if (similarList.size() == 0) {
|
|
return "Cannot find topic \"" + topic + "\", please try a different spelling.";
|
|
}
|
|
StringBuilder sb = new StringBuilder();
|
|
sb.append("Topic not found, did you mean:\n");
|
|
for (JsonElement similarItem : similarList) {
|
|
sb.append("- ").append(similarItem.getAsString()).append("\n");
|
|
}
|
|
return sb.toString();
|
|
}
|
|
return res.get("extract").getAsString();
|
|
}
|
|
|
|
private static String wikiApiCall(String url) {
|
|
HttpClient client = HttpClient.newHttpClient();
|
|
HttpRequest request = HttpRequest.newBuilder()
|
|
.GET()
|
|
.header("Accept", "application/json")
|
|
.uri(URI.create(url))
|
|
.build();
|
|
HttpResponse<String> response;
|
|
try {
|
|
response = client.send(request, HttpResponse.BodyHandlers.ofString());
|
|
HttpHeaders headers = response.headers();
|
|
if ((response.statusCode() > 299 && response.statusCode() < 400) && headers.firstValue("location").isPresent()) {
|
|
return followRedirect(headers.firstValue("location").get());
|
|
}
|
|
return response.body();
|
|
} catch (IOException | InterruptedException e) {
|
|
e.printStackTrace();
|
|
return "Error making request: " + e.getMessage();
|
|
}
|
|
}
|
|
|
|
private static String followRedirect(String redirectedUrl) {
|
|
return wikiApiCall("https://en.wikipedia.org/api/rest_v1/page/summary/" + redirectedUrl);
|
|
}
|
|
}
|