Minecraft Server Status Abfragen

spark

Mitglied
Ich versuche gerade einen Status von einem Minecraft Server abzufragen mithilfe einer API. Ich bekomme eine Antwort, jedoch weiß ich nicht, wie ich diese (das JSON File) auslesen kann. Soweit ist mein Code:
Java:
private static HttpURLConnection connection;
    
    public static void main(String[] args) {
        BufferedReader reader;
        String line;
        StringBuffer responseContent = new StringBuffer();
        
        try {
            URL url = new URL("https://api.mcsrvstat.us/2/hypixel.net");
            connection = (HttpURLConnection) url.openConnection();
            
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            
            int status = connection.getResponseCode();
            //System.out.println(status);
            if(status > 299) {
                reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
                while((line = reader.readLine()) != null) {
                    responseContent.append(line);
                }
                reader.close();
            }else {
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                while((line = reader.readLine()) != null) {
                    responseContent.append(line);
                }
                reader.close();
            }
            System.out.println(responseContent.toString());
            parse(responseContent.toString());
            
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            connection.disconnect();
        }

    }
Weiß jemand, wie ich die Antwort auslesen kann und dann zum Beispiel einen Boolean haben kann mit online true/false?
LG
 
Beste Antwort
Ich habe das Ganze nun so gelöst:
Java:
private static HttpURLConnection connection;
   
    public static void main(String[] args) {
        BufferedReader reader;
        String line;
        StringBuffer responseContent = new StringBuffer();
        try {
            URL url = new URL("https://api.mcsrvstat.us/2/SurvivalExtrem.nitrado.net:10040");
            connection = (HttpURLConnection) url.openConnection();
           
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
           
            int status = connection.getResponseCode();
            if(status > 299) {
                reader = new BufferedReader(new...
JSON lässt sich einfach in ein Java-Object umwandeln. Hier ein einfaches Beispiel:
XML:
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.11.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.14.1</version>
</dependency>
Java:
String json = IOUtils.toString(url, StandardCharsets.UTF_8);
ObjectMapper mapper = new ObjectMapper();
Person user = mapper.readValue(json, Person.class);

System.out.println(user.name); //e.g. John
Um eine detailierte Antwort zu geben wäre es gut, wenn du ein JSON-Beispiel hier veröffentlichen könntest.
 
Zuletzt bearbeitet:
Danke für die Antwort.
JSON:
{
    "online": true,
    "ip": "127.0.0.1",
    "port": 25567,
    "debug": { //See section below for information about the values
        "ping": true,
        "query": true,
        "srv": true,
        "querymismatch": false,
        "ipinsrv": false,
        "cnameinsrv": false,
        "animatedmotd": false,
        "cachetime": 1518553220,
        "cacheexpire": 1518553280,
        "apiversion": 2
    },
    "motd": {
        "raw": [
            "\u00a7cEver\u00a7r\u00a79PvP \u00a7r\u00a77- \u00a7r\u00a72\u00c9n server, for alle",
            "\u00a7r\u00a7fSe dine stats p\u00e5 \u00a7r\u00a76stats.everpvp.dk\u00a7r"
        ],
        "clean": [
            "EverPvP - \u00c9n server, for alle",
            "Se dine stats p\u00e5 stats.everpvp.dk"
        ],
        "html": [
            "<span style=\"color: #FF5555\">Ever<\/span><span style=\"color: #5555FF\">PvP <\/span><span style=\"color: #AAAAAA\">- <\/span><span style=\"color: #00AA00\">\u00c9n server, for alle<\/span>",
            "<span style=\"color: #FFFFFF\">Se dine stats p\u00e5 <\/span><span style=\"color: #FFAA00\">stats.everpvp.dk<\/span>"
        ]
    },
    "players": {
        "online": 2,
        "max": 100,
        "list": [ //Only included when there are any players
            "Spirit55555",
            "sarsum33"
        ],
        "uuid": { //Only included when ping is used and players are returned (may not contain all players)
            "Spirit55555": "f6792ad3-cbb4-4596-8296-749ee4158f97",
            "sarsum33": "d3512599-d4d9-4520-808f-a81f4cdfe8d0"
        }
    },
    "version": "1.12", //Could include multiple versions or additional text
    "protocol": 332, //Only included when ping is used, see more here: http://wiki.vg/Protocol_version_numbers
    "hostname": "server.mymcserver.tld", //Only included when a hostname is detected
    "icon": "data:image\/png;base64,iVBORw0KGgoAAAANSUhEU...dSk6AAAAAElFTkSuQmCC", //Only included when an icon is detected
    "software": "BungeeCord", //Only included when software is detected
    "map": "MyMcWorld",
    "gamemode": "Survival", //Only included for Bedrock servers
    "serverid": "2438134582716697305", //Only included for Bedrock servers
    "plugins": { //Only included when plugins are detected
        "names": [
            "WordEdit",
            "WorldGuard"
        ],
        "raw": [
            "WordEdit 6.1.5",
            "WorldGuard 6.2"
        ]
    },
    "mods": { //Only included when mods are detected
        "names": [
            "BiomesOPlenty",
            "MoreFurnaces"
        ],
        "raw": [
            "BiomesOPlenty 2.1.0",
            "MoreFurnaces 1.3.9"
        ]
    },
    "info": { //Only included when detecting that the player samples are used for information
        "raw": [
            "\u00a77\u00bb \u00a7cKitPvP \u00a77:: \u00a7f1 \u00a77online",
            "\u00a77\u00bb \u00a7bSurvivalGames \u00a77:: \u00a7f0 \u00a77online"
        ],
        "clean": [
            "\u00bb KitPvP :: 1 online",
            "\u00bb SurvivalGames :: 0 online"
        ],
        "html": [
            "<span style=\"color: #AAAAAA\">\u00bb <\/span><span style=\"color: #FF5555\">KitPvP <\/span><span style=\"color: #AAAAAA\">:: <\/span><span style=\"color: #FFFFFF\">1 <\/span><span style=\"color: #AAAAAA\">online<\/span>",
            "<span style=\"color: #AAAAAA\">\u00bb <\/span><span style=\"color: #55FFFF\">SurvivalGames <\/span><span style=\"color: #AAAAAA\">:: <\/span><span style=\"color: #FFFFFF\">0 <\/span><span style=\"color: #AAAAAA\">online<\/span>"
        ]
    }
}
So könnte die JSON Datei aussehen und ich versuche beispielsweise dann die Anzahl der Spieler welche gerade online sind in einem int zu speichern.
 
Das kann man ja etwas nachbilden. Dabei sollte es ausreichen, die Felder zu nutzen, die Du wirklich brauchst. Du hast also eine klasse, in der Du z.B. die folgenden Felder hast:
  • boolean online
  • String ip
  • int port
  • Players players
  • String versuib
  • int protocol
  • String hostname

Die Klasse Players hat dann
  • int online
  • int max
  • List<String> list
  • List<String> uuid

Wenn Du etwas nicht brauchst, dann kannst Du es weglassen.

Damit hast Du dann die Typen, die Du verwenden kannst - du holst dir die Antwort einfach als Typ, den Du da als erstes erstellt hast also StateResult.class wenn du die Klasse StateResult genannt hast.
 
Du hast doch schon den konkreten Code:
  • Du bekommst in Deiner Abfrage ja bereits die Informationen als JSON
  • @Oneixee5 hat Dir den Code gezeigt, wie Du aus einem JSON String ein konkretes Objekt bekommen kannst. Da wurde eine Klasse Person im Code verwendet, aber das ist ja jetzt ersetzbar.
  • Ich habe dir jetzt den Aufbau von zwei Klassen gegeben. Diese musst Du nur erstellen. Dann kannst Du den Code von @Oneixee5 direkt verwenden und musst nur die Klasse entsprechend anpassen.
 
Ich habe das Ganze nun so gelöst:
Java:
private static HttpURLConnection connection;
   
    public static void main(String[] args) {
        BufferedReader reader;
        String line;
        StringBuffer responseContent = new StringBuffer();
        try {
            URL url = new URL("https://api.mcsrvstat.us/2/SurvivalExtrem.nitrado.net:10040");
            connection = (HttpURLConnection) url.openConnection();
           
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
           
            int status = connection.getResponseCode();
            if(status > 299) {
                reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
                while((line = reader.readLine()) != null) {
                    responseContent.append(line);
                }
                reader.close();
            }else {
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                while((line = reader.readLine()) != null) {
                    responseContent.append(line);
                }
                reader.close();
            }
                       
            JSONObject js = new JSONObject(responseContent.toString());

            Boolean online = (Boolean) js.get("online");
            JSONObject players = (JSONObject) js.get("players");
            int playeron = (int) players.get("online");
            int playermax = (int) players.get("max");
            JSONArray list = players.getJSONArray("list");
            String[] spieler = new String[list.length()];

            for(int i = 0; i<list.length(); i++) {
                spieler[i] = list.toString();
            }          
                 
            System.out.println("Ist der Server online: "+online);
            System.out.println("Anzahl der Spieler welche im Moment online sind: "+playeron);
            System.out.println("Maximale Spieleranzahl: "+playermax);
                       
            System.out.println("Spieler: "+spieler[1]);
           

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            connection.disconnect();
        }

    }
Man muss nur die Json library hinzufügen
 
Beste Antwort

Zurück
Oben