Skip to content

Instantly share code, notes, and snippets.

@FabulousCodingFox
Created April 1, 2022 19:14
Show Gist options
  • Save FabulousCodingFox/e38b4b124329cbe1a91505a79ddd61a2 to your computer and use it in GitHub Desktop.
Save FabulousCodingFox/e38b4b124329cbe1a91505a79ddd61a2 to your computer and use it in GitHub Desktop.
Quick snippet to get the skin of a player by name using the Mojang api
package net.sulfurium.sulfuriumlib.Utils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
public class SkinUtils {
public static String[] getSkin(String name) {
String uuid;
try {
HttpsURLConnection connection = (HttpsURLConnection) new URL(String.format("https://api.mojang.com/users/profiles/minecraft/%s", name)).openConnection();
if (connection.getResponseCode() == HttpsURLConnection.HTTP_OK) {
String reply = new BufferedReader(new InputStreamReader(connection.getInputStream())).readLine();
uuid = reply.split("\"id\":\"")[1].split("\"")[0];
} else {
return new String[]{null,null};
}
} catch (IOException e) {Logger.warn(e.toString()); return new String[]{null,null};}
try {
HttpsURLConnection connection = (HttpsURLConnection) new URL(String.format("https://sessionserver.mojang.com/session/minecraft/profile/%s?unsigned=false", uuid)).openConnection();
if (connection.getResponseCode() == HttpsURLConnection.HTTP_OK) {
String reply = readAllLines(new BufferedReader(new InputStreamReader(connection.getInputStream()))).replace("\n","").replace(" ","");
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(reply);
JSONArray properties = (JSONArray) json.get("properties");
JSONObject propertyTex = (JSONObject) properties.get(0);
String skin = (String) propertyTex.get("value");
String signature = (String) propertyTex.get("signature");
return new String[]{skin,signature};
} else {
Logger.warn("Connection could not be opened (Response code " + connection.getResponseCode() + ", " + connection.getResponseMessage() + ")");
}
} catch (IOException | ParseException e) {Logger.warn(e.toString());}
return new String[]{null,null};
}
private static String readAllLines(BufferedReader reader) throws IOException {
StringBuilder content = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {content.append(line);content.append(System.lineSeparator());}
return content.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment