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

Android: StatusLine now deprecated, what is the alternative?

Google 表示 StatusLine 现在已弃用,根据此 link:https://developer.android.com/sdk/api_diff/22/changes/org.apache.http.StatusLine.html

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

它有哪些替代方案?

谢谢

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

由于性能和其他问题,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
    }
}