Just use
return ma.toString();
代替
return ma;
ma.toString()
返回 StringBuilder 的字符串表示形式。
See StringBuilder#toString() http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/StringBuilder.html#toString()欲了解详情
正如 Valeri Atamaniouk 在评论中建议的那样,您还应该在catch
块,否则你会得到一个编译器错误missing return statement
,所以编辑
} catch (Exception e) {
Log.e("ERR",e.getMessage());
}
to
} catch (Exception e) {
Log.e("ERR",e.getMessage());
return null; //or maybe return another string
}
将是一个好主意。
EDIT
正如 Esailija 所建议的,我们在这段代码中有三个反模式
} catch (Exception e) { //You should catch the specific exception
Log.e("ERR",e.getMessage()); //Don't log the exception, throw it and let the caller handle it
return null; //Don't return null if it is unnecessary
}
所以我认为最好做这样的事情:
private static String getUrlSource(String url) throws MalformedURLException, IOException {
URL localUrl = null;
localUrl = new URL(url);
URLConnection conn = localUrl.openConnection();
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line = "";
String html;
StringBuilder ma = new StringBuilder();
while ((line = reader.readLine()) != null) {
ma.append(line);
}
return ma.toString();
}
然后,当你调用它时:
try {
String urlSource = getUrlSource("http://www.google.com");
//process your url source
} catch (MalformedURLException ex) {
//your url is wrong, do some stuff here
} catch (IOException ex) {
//I/O operations were interrupted, do some stuff here
}
检查以下链接以获取有关 Java 反模式的更多详细信息:
- Java 反模式 http://www.odi.ch/prog/design/newbies.php
- 编程反模式 http://www.javacodegeeks.com/2011/10/programming-antipatterns.html
- Java 应用程序中的反模式简介 http://www.devx.com/Java/Article/29162