As I’ve seen many need, as well as me, a way to grab UUIDs from players who aren’t online and who have never visited the server before, I’ve decided to write these easy methods to help those who may need them. Now my methods of grabbing the UUIDs involve grabbing the json strings created by api.mojang.com, so an internet connection is required for this to work. While the UUID is correct from the website, it does not include any of the hyphens you might see when you use .getUniqueId() in sponge, but I also wrote a way to add those into a new string.
This class/methods can also be viewed here for those who like gists.
public String getUUID(String name){
if(isAPIOnline()){
try{
URL url = new URL("https://api.mojang.com/users/profiles/minecraft/" + name + "?at=" + Instant.now() .getEpochSecond());
URLConnection conn = url.openConnection();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
JsonElement je = new JsonParser().parse(rd.readLine());
//UUID without hyphens.
String sUUID = je.getAsJsonObject().get("id").getAsString();
//UUID with hyphens, this is optional but this is the kind of UUID sponge uses.
String uuid =
sUUID.substring(0, Math.min(sUUID.length(), 8))
+ "-"
+ sUUID.substring(8, Math.min(sUUID.length(), 12))
+ "-"
+ sUUID.substring(12, Math.min(sUUID.length(), 16))
+ "-"
+ sUUID.substring(16, Math.min(sUUID.length(), 20))
+ "-"
+ sUUID.substring(20, Math.min(sUUID.length(), 32));
rd.close();
//You can return sUUID or uuid, whichever you prefer.
return uuid;
}catch(Exception e){
//Print stack trace if wanted.
e.printStackTrace();
}
}
//Return servers are unavailable here
return null;
}
//And also to determine if Mojang API is available
public boolean isAPIOnline(){
try{
//2000 is just the timeout, in milliseconds, you can change it to what you want.
if(InetAddress.getByName("52.85.70.110").isReachable(2000)){
return true;
}
}catch(Exception e){
//Print stack trace if wanted.
e.printStackTrace();
}
return false;
}
If i made any typos, sorry, but if I did it should be fairly obvious once you get them inside your IDE. Also my methods of obtaining the UUID may be frowned upon by MCs new name changing system but this method has seemed to work for me.