Advertisement
notjacob

API REQUEST GET

Mar 7th, 2020
2,158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.04 KB | None | 0 0
  1. public class MojangAPI {
  2.     private static final String USER_API_REQ = "https://api.mojang.com/users/profiles/minecraft/%s";
  3.  
  4.     private Map<String, UUID> responseCache = new ConcurrentHashMap<String, UUID>();
  5.  
  6.     private UUID getOfflineUUID(String name) {
  7.         if (!responseCache.containsKey(name)) {
  8.             try {
  9.                 HttpURLConnection con = (HttpURLConnection) new URL(String.format(USER_API_REQ, name)).openConnection();
  10.                 con.setRequestMethod("GET");
  11.                 int code = con.getResponseCode();
  12.                 if (code == 204) {
  13.                     System.out.println("Mojang API server returned 204 code! (User does not exist!)");
  14.                     return null;
  15.                 } else if (code == 404) {
  16.                     System.out.println("Mojang API returned 404! (Server not found)");
  17.                 }
  18.                 InputStreamReader reader = new InputStreamReader(con.getInputStream());
  19.                 JsonElement element = new JsonParser().parse(reader);
  20.                 if (element.isJsonArray()) {
  21.                     System.out.println("Link returned invalid JSON (returned an array)");
  22.                     return null;
  23.                 }
  24.                 reader.close();
  25.                 JsonObject obj = element.getAsJsonArray().get(0).getAsJsonObject();
  26.                 UUID finallly = UUID.fromString(obj.get("id").getAsString());
  27.                 responseCache.put(name, finallly);
  28.                 return finallly;
  29.             } catch (Exception e) {
  30.                 e.printStackTrace();
  31.             }
  32.             return null;
  33.         } else {
  34.             return responseCache.get(name);
  35.         }
  36.     }
  37.  
  38.     public UUID getOfflineUUIDAsync(String name) {
  39.         CompletableFuture<UUID> unique = CompletableFuture.supplyAsync(() -> getOfflineUUID(name), Constants.DEFAULT_THREAD_POOL);
  40.         try {
  41.             return unique.get();
  42.         } catch (InterruptedException | ExecutionException e) {
  43.             e.printStackTrace();
  44.         }
  45.         return null;
  46.     }
  47.  
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement