String von Webseite herunterladen

LuAl

Neues Mitglied
Guten Tag,

ich bin neu hier im Forum und ich hoffe ihr könnt mir helfen: Seit nun mehreren Stunden versuche ich verzweifelt den Inhalt der Seite http://mcpvp.com/api/ping.json herunterzuladen. Das Problem ist, dass ich immer irgendwelche Hyroglyphen herausbekomme, die ich natürlich in nach JSON decoden kann. Ich habe bereits alle, mir bekannten, charsets ausprobiert, es aber immer noch nicht geschafft.

Das ist mein bisheriger Ansatz:
Java:
String text = new String(Utils.download("http://mcpvp.com/api/ping.json").getBytes(), "Iso-8859-1");

Utils Klasse (ausschnitt):
public class Utils {
public static String download(String path) throws IOException {
InputStream s = null;
String content = null;
try {
s = (InputStream)new URL(path).getContent();
content = IOUtils.toString(s, "UTF-8");
}
finally {
if (s != null) s.close();
}
if (content == null) return null;


return content.toString();
}
}

Java:
Mfg LuAl
 
Ok, das habe ich umgesetzt. Nun habe ich aber immer noch das oben genannte Problem. Ich glaube es handelt sich um gzip. Wie kann ich das nun in einen simplen Stirng verwandeln?

Mfg Lukas
 
Das hier ist eine Methode, die ich selber in meinen Programmen nutze. Ich habe sie von einem Member auf StackOverflow bekommen. Sie funktioniert super.

Ich empfehle dir, die Methode in eine Extra-Klasse zu schreiben, und diese static lassen, damit du sie (ggf.) auch in anderen Klassen verwenden kannst.

Java:
/**
     * Downloads webpages from the interwebs and returns the String value.
     *
     * @param url
     * @return
     */
    public static String getPage(URL url) {
        String content = null;
        int MAX_PAGE_SIZE = 1000000;
        try {
            // try opening the URL
            URLConnection urlConnection = url.openConnection();
            urlConnection.setAllowUserInteraction(false);

            InputStream urlStream = url.openStream();
            byte buffer[] = new byte[1000];
            int numRead = urlStream.read(buffer);
            content = new String(buffer, 0, numRead);

            while ((numRead != -1) && (content.length() < MAX_PAGE_SIZE)) {
                numRead = urlStream.read(buffer);
                if (numRead != -1) {
                    String newContent = new String(buffer, 0, numRead);
                    content += newContent;
                }
            }
        } catch (IOException | IndexOutOfBoundsException ex) {
            appendLog("ERROR: Error while downloading from external source!");
            appendLog(ex.toString());
            return null;
        }
        return content;
    }
 

Zurück
Oben