Trying to read from a URL(in Java) produces gibberish on certain occaisions

后端 未结 4 803
清歌不尽
清歌不尽 2021-01-23 07:43

I\'m trying to read from a URL, and then print the result.

BufferedReader in = new BufferedReader(
     new InputStreamReader(new URL(\"http://somesite.com/\").o         


        
4条回答
  •  失恋的感觉
    2021-01-23 08:12

    So after much searching I found the answer to this. The xml is read as gibberish because it is Gzip compressed. The way to read this is by using the GZIPInputStream. This is because the XML is compressed differently.

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("Accept-Encoding", "gzip");
        InputStreamReader in = new InputStreamReader (new GZIPInputStream(connection.getInputStream()));
        String str;            
        while (true) {
     int ch = in.read();
     if (ch==-1) {
        break;
     }
    

提交回复
热议问题