开发者

Better and a Faster way to read a string from a URL

开发者 https://www.devze.com 2023-04-09 05:19 出处:网络
I am using this code to read content from a given URL. Is there and faster and better way to do it? private static String readUrl(String urlString) throws Exception {

I am using this code to read content from a given URL. Is there and faster and better way to do it?

private static String readUrl(String urlString) throws Exception {
    BufferedReader reader = null;
    try {
        URL url = new URL(urlString);
        reader = new BufferedReader(new InputStreamReader(url.openStream()));
        StringBuffer buffer = new StringBuffe开发者_运维知识库r();
        int read;
        char[] chars = new char[1024];
        while ((read = reader.read(chars)) != -1)
            buffer.append(chars, 0, read); 

        return buffer.toString();
    } finally {
        if (reader != null)
            reader.close();
    }
}


Use StringBuilder instead of StringBuffer


Is this an HTTP URL? If yes, then you

  • must look at the Content-Type header and ensure that you're applying a correct encoding to the stream. As it is, you're applying the default encoding of your particular JVM installation, which may not correspond to what the server is sending
  • should look at the Content-Length header to pre-size your buffer.

Other than those two changes, there's not much opportunity to speed up bytes across the network.

Edit: you could also use Jakarta Commmons IOUtils.toString() to read the stream. This will reduce the amount of code that you have to write (and may be presumed fully debugged). However, it will have to resize buffers along the way.


Well there are libs / source available online that will do this for you:

http://json.org/java/


You can also use "BufferedReader.readLine()"

0

精彩评论

暂无评论...
验证码 换一张
取 消