Skip to content

Instantly share code, notes, and snippets.

@intronate67
Last active November 30, 2016 22:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save intronate67/1a1d503273304494d8b2d19034857ea7 to your computer and use it in GitHub Desktop.
Save intronate67/1a1d503273304494d8b2d19034857ea7 to your computer and use it in GitHub Desktop.
/*Class is not intended to be used as an instance.
* Please copy methods inside your own plugin as this does not
* contain a constructor, no one is stopping you from adding one
* though.
* This code is free to use for everyone, forever.
*/
public class UUIDGetter{
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;
}
//Use 'getUUID("USERNAME_HERE");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment