0

我正在寻找一种最佳实践来处理 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();
}
4

1 回答 1

1

您将使用 connection.getResponseCode() 获得不同的响应代码 检查主机不可用的响应代码,您将被设置。

于 2013-02-06T19:16:26.383 回答