将url内容读入String

时间:2014-03-28 06:16:03

标签: java

我正在通过以下方法阅读缓冲阅读器的内容:

public static String readBuffer(Reader reader, int limit) throws IOException 
{           
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < limit; i++) {
        int c = reader.read();
            if (c == -1) {
                return ((sb.length() > 0) ? sb.toString() : null);
            }
        if (((char) c == '\n') || ((char) c == '\r')) {
            break;
    }
        sb.append((char) c);
}
    return sb.toString();
}   

我稍后会调用此方法来测试 -

URL url = new URL("http://www.oracle.com/");
    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));        
    StringBuffer sb = new StringBuffer();
    String line=null;
    while((line=readBuffer(in, 2048))!=null) {
        sb.append(line);
    }
    System.out.println(sb.toString());

我的问题是,我在第一个方法中将bufferedreader的内容返回到一个字符串中,然后在第二个方法中将这些String内容再次附加到StringBuffer中,然后读出它。这是正确的方法吗?任何其他方式我可以读取包含来自url的内容的字符串内容?请告知。

1 个答案:

答案 0 :(得分:0)

我希望这有效 -

public static String readFromURL(){
    URL url = new URL("http://www.oracle.com/");
    StringBuilder responseBuilder = new StringBuilder();
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
    httpCon.setDoOutput(true);
    httpCon.setDoInput(true);

    int resCode = httpCon.getResponseCode();
    InputStream is = null;
    if (resCode == 200) {
         is = httpCon.getInputStream();
         BufferedReader reader = new BufferedReader(
                 new InputStreamReader(is));
         String response = null;
         while (true) {
             response = reader.readLine();
             if (response == null)
                 break;
             responseBuilder.append(response);
         }
    }
    return responseBuilder.toString();
}

public static String readFromURL(){ URL url = new URL("http://www.oracle.com/"); StringBuilder responseBuilder = new StringBuilder(); HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); httpCon.setDoOutput(true); httpCon.setDoInput(true); int resCode = httpCon.getResponseCode(); InputStream is = null; if (resCode == 200) { is = httpCon.getInputStream(); BufferedReader reader = new BufferedReader( new InputStreamReader(is)); String response = null; while (true) { response = reader.readLine(); if (response == null) break; responseBuilder.append(response); } } return responseBuilder.toString(); }