Ответ 1
Просто используйте
return ma.toString();
вместо
return ma;
ma.toString()
возвращает строковое представление для вашего StringBuilder.
Подробнее см. StringBuilder # toString()
Как предложил Валери Атаманюк в комментариях, вы также должны вернуть что-то в блоке catch
, иначе вы получите ошибку компилятора для missing return statement
, поэтому редактирование
} catch (Exception e) {
Log.e("ERR",e.getMessage());
}
к
} catch (Exception e) {
Log.e("ERR",e.getMessage());
return null; //or maybe return another string
}
Было бы неплохо.
ИЗМЕНИТЬ
Как предположил 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 Anti-Patterns: