Ben*_*n S 2 java string optimization inputstream micro-optimization
我有以下Java代码来获取给定URL的HTML页面的全部内容.这可以以更有效的方式完成吗?欢迎任何改进.
public static String getHTML(final String url) throws IOException {
if (url == null || url.length() == 0) {
throw new IllegalArgumentException("url cannot be null or empty");
}
final HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
final BufferedReader buf = new BufferedReader(new InputStreamReader(conn.getInputStream()));
final StringBuilder page = new StringBuilder();
final String lineEnd = System.getProperty("line.separator");
String line;
try {
while (true) {
line = buf.readLine();
if (line == null) {
break;
}
page.append(line).append(lineEnd);
}
} finally {
buf.close();
}
return page.toString();
}
Run Code Online (Sandbox Code Playgroud)
我不禁觉得线读不是最佳.我知道我可能正在屏蔽MalformedURLException由openConnection电话引起的问题,我对此感到满意.
我的函数还有使HTML字符串具有当前系统的正确行终止符的副作用.这不是必需的.
我意识到网络IO可能会缩短读取HTML所需的时间,但我仍然想知道这是最佳的.
在旁注:如果StringBuilder有一个打开的构造函数,InputStream它会简单地获取所有内容InputStream并将其读入其中,这将是非常棒的StringBuilder.
Bor*_*zic 10
从其他答案中可以看出,在任何强大的解决方案中都应该考虑许多不同的边缘情况(HTTP特性,编码,分块等).因此,我建议除玩具程序之外的任何东西都使用事实上的Java标准HTTP库:Apache HTTP Components HTTP Client.
他们提供了许多样本,"只是"获取请求的响应内容如下所示:
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://www.google.com/");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httpget, responseHandler);
// responseBody now contains the contents of the page
System.out.println(responseBody);
httpclient.getConnectionManager().shutdown();
Run Code Online (Sandbox Code Playgroud)