Android:StatusLine现已弃用,有什么替代方案?

时间:2015-08-22 13:46:09

标签: android deprecated statusline

谷歌表示StatusLine现已弃用,根据以下链接:https://developer.android.com/sdk/api_diff/22/changes/org.apache.http.StatusLine.html

我想要一段代码来了解服务器响应的状态代码,而不是已弃用的代码。

有什么替代方案?

谢谢

2 个答案:

答案 0 :(得分:0)

使用URL.openConnection()。更多详情here

答案 1 :(得分:0)

由于性能和其他问题,org.apache.http软件包已弃用了一段时间,现在已从API级别23开始完全删除。

你应该使用HttpURLConnection,它有一个很好的文档指导你完成整个过程。

如果您需要状态代码,请在HttpURLConnection实例上调用getResponseCode()

以下是示例代码:

@Nullable
public NetworkResponse openUrl(@NonNull String urlStr) {
    URL url = new URL(urlStr);
    // for secure connections, use this: HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    String networkErrorStr;

    try {
        int responseCode = connection.getResponseCode();

        InputStream er = connection.getErrorStream();

        if (er != null) {
            // if you get here, you'll anticipate an error, for example 404, 500, etc.
            networkErrorStr = getResponse(er); // save the error message
        }

        InputStream is = connection.getInputStream(); // this will throw an exception if the previous getErrorStream() wasn't null
        String responseStr = getResponse(is); // the actual response string on success

        return new NetworkResponse(responseCode, responseStr);
    } catch (Exception e) {
        try {
            if (connection != null) {
                // you have to call it again because the connection is now set to error mode
                int code = connection.getResponseCode();

                return new NetworkResponse(code, networkErrorStr); // response on error
            }
        } catch (Exception e1) {
            e1.printStackTrace(); // for debug purposes
        }
        e.printStackTrace(); // for debug purposes
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }

    return null;
}

private String getResponse(InputStream is) throws IOException {
    StringBuilder builder = new StringBuilder();
    InputStreamReader isr = new InputStreamReader(is, "UTF-8");
    BufferedReader reader = new BufferedReader(isr);

    String line;

    while ((line = reader.readLine()) != null) {
        builder.append(line);
    }

    return builder.toString();
}

public static class NetworkResponse { // it is static because you will use it inside a class probably
    public NetworkResponse(int code, @Nullable String str) {
        // do whatever you want with the data
    }
}