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

后端 未结 4 882
清歌不尽
清歌不尽 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:00

    I had the same issue until I used HttpURLConnection with setChunkedStreamingMode set.

                HttpURLConnection connection = (HttpURLConnection)serverAddress.openConnection();
                connection.setRequestMethod("GET");
                connection.setDoOutput(true);
                connection.setReadTimeout(2000);
                connection.setChunkedStreamingMode(0);
    
                connection.connect();
    
                BufferedReader rd  = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    
                String line = "";
    
                while ((line = rd.readLine()) != null)
                {
                    sb.append(line);
                }
    
                System.out.println(sb.toString());
    

提交回复
热议问题