我正在寻找最佳做法来处理HttpURLConnection中的错误,尤其是在主机不可用的情况下。我是如何改变我的来源的?:
protected String doInBackground(String... strings) {
URL aURL;
String line;
HttpURLConnection connection;
BufferedReader reader;
StringBuilder stringBuilder = null;
try {
aURL = new URL(strings[0]);
connection = (HttpURLConnection) aURL.openConnection();
InputStream aInputStream = connection.getInputStream();
BufferedInputStream aBufferedInputStream = new BufferedInputStream(aInputStream);
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
stringBuilder = new StringBuilder();
while ((line = reader.readLine()) != null)
{
stringBuilder.append(line);
}
} catch (IOException e) {
Log.d("svc", e.toString());
}
return stringBuilder.toString();
}
答案 0 :(得分:1)
您将使用connection.getResponseCode()获得不同的响应代码 检查主机的响应代码不可用,您将被设置。