It would be safer to close your stream using a try..finally
block. You might also use a StringBuilder
as it is designed for concatenating strings. You should also avoid catching Exception
and doing nothing with it. Also, your code is concatenating lines without any line-breaks. This may well not be what you want, in which case append("
")
when you read each line in.
Here's a version with those modifications:
StringBuilder json = new StringBuilder();
try {
URL url = new URL(sMyUrl);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
try {
String str;
while ((str = in.readLine()) != null) {
json.append(str).append("
");
}
} finally {
in.close();
}
} catch (Exception e) {
throw new RuntimeException("Failed to read JSON from stream", e);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…