用于WebService调用的哪一个 - HttpURLConnection或DefaultHttpClient



我在我的应用程序中只使用了DefaultHttpClient for WebService调用。但是由于DefaultHttpClient已被弃用,我对使用什么感到困惑。我想从中选择最好的,以便进一步发展。还建议我是否有任何其他调用Web服务的最佳方法。

DefaultHttpClient是一种仍在使用的Apache库,但如今,HttpURLConnection诞生了,谷歌推荐它,因为它比Apache库更适合移动应用程序。DefaultHttpClient 也可以在 android 环境中使用,但在 android 中,它已被弃用,我们应该使用 HttpUrlConnection 具有许多优点:适合限制 android 内存,适合电池......它会发现它使用起来不太困难,下面是一些有用的代码

 URL url = new URL(requestUrl);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setConnectTimeout(CONNECT_TIME_OUT);
    connection.setReadTimeout(READ_TIME_OUT);
    connection.setUseCaches(false);
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=" + CHARSET);
    connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParams.getBytes().length));
    if (headers != null) addHeaderFields(connection, headers);
    if (!TextUtils.isEmpty(urlParams)) {
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), CHARSET), true);
        writer.append(urlParams);
        writer.flush();
        writer.close();
    }
    StringBuilder response = new StringBuilder();
    // checks server's status code first
    int status = connection.getResponseCode();
    if (status == HttpURLConnection.HTTP_OK) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));
        String line = null;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
        connection.disconnect();
    } else {
        throw new ApiException(ApiException.APP_EXCEPTION, "Server returned non-OK status: " + status);
    }
    return response.toString();

因为Android已经弃用了DefaultHTTPClient类和方法。
Android 6.0 版本删除了对 Apache HTTP 客户端的支持。如果您的应用使用此客户端并面向 Android 2.3(API 级别 9)或更高版本,请改用 HttpURLConnection 类。此 API 效率更高,因为它通过透明压缩和响应缓存减少了网络使用,并最大限度地减少了功耗。
要继续使用 Apache HTTP API,您必须首先在 build.gradle 文件中声明以下编译时依赖项:

android {
    useLibrary 'org.apache.http.legacy'
}

这是URL,您可以从中获取有关HttpURLConnection的更多详细信息。https://developer.android.com/reference/java/net/HttpURLConnection.html

DefaultHTTPClient 在 android 中已弃用,在 Marshmallow(Android 6.0)及其之后的 API 中将不再受支持。HTTPURLConnection 优于 HTTPClient。

对于网络操作,我建议您使用Volley,Android的官方网络相关调优库。它简化了网络调用的方式,速度更快,而且默认情况下它的操作是异步的(您无需担心网络调用的自定义线程)。

这里有一个使用Volley的好教程:Android使用Volley库

安卓凌空指南:使用凌空传输网络数据

最新更新