Android的网络连接HttpUrlConnection

Android官方在23版就不要HttpClient了。
呵呵,以前的代码要重写了吧!
虽然还有解决办法让你继续用原来的,加下面这句。

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

但既然官方都这么搞了,那么我们就还是用回HttpUrlConnetction把!
关于这两者的说法,请跳到最下面点连接看把。

使用HttpUrlConnection

我们来看下怎么用HttpUrlConnection实在点,
反正结论是开发Android用这个的结论就对了,要不然人家取消httpClient干嘛。

eg:

HttpUrlConnectionClient httpEngine = HttpUrlConnectionClient.getInstance();
Map<String, String> paramMap = new HashMap<String, String>();
paramMap.put("name", "user1");
paramMap.put("method", "region");
paramMap.put("phoneNum", "110");

httpEngine.postHandle(paramMap, type);

我们的HttpUrlConnectionClient类

public class HttpUrlConnectionClient {

    private final static String SERVER_URL = "www.yourServer.com";
    private final static String REQUEST_MOTHOD = "POST";
    private final static String ENCODE_TYPE_UTF_8 = "UTF-8";
    private final static int TIME_OUT = 15000;

    private static HttpUrlConnectionClient instance = null;

    private HttpUrlConnectionClient() {

    }

    public static HttpUrlConnectionClient getInstance() {
        if (instance == null) {
            instance = new HttpUrlConnectionClient();
        }
        return instance;
    }

    //Map<String, String> paramsMap 传入参数
    //还是觉得basicValuePair挺好的。
    public string postHandle(Map<String, String> paramsMap ) throws IOException {
        String data = joinParams(paramsMap); 
        HttpURLConnection connection = getConnection();
        connection.setRequestProperty("Content-Length", String.valueOf(data.getBytes().length));
        connection.connect();

        OutputStream os = connection.getOutputStream();
        os.write(data.getBytes());
        os.flush();

        if (connection.getResponseCode() == 200) { 
            InputStream is = connection.getInputStream(); 
            ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
            int len = 0; 
            byte buffer[] = new byte[1024]; 
            while ((len = is.read(buffer)) != -1) {
                // 根据读取的长度写入到os对象中
                baos.write(buffer, 0, len);
            } 
            is.close();
            baos.close();
            connection.disconnect();

            final String result = new String(baos.toByteArray()); 
            Log.i(TAG, "response: " + result);
            return result;
        } else {
            connection.disconnect();
            return null;
        }
    }

    // 获取connection
    private HttpURLConnection getConnection() {
        HttpURLConnection connection = null; 
        try { 
            URL url = new URL(SERVER_URL); 
            connection = (HttpURLConnection) url.openConnection(); 
            connection.setRequestMethod(REQUEST_MOTHOD);
            // 发送POST请求必须设置允许输入,默认为true
            connection.setDoInput(true);
            // 发送POST请求必须设置允许输出
            connection.setDoOutput(true);
            // 设置不使用缓存
            connection.setUseCaches(false); 
            connection.setReadTimeout(TIME_OUT);
            connection.setConnectTimeout(TIME_OUT);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Connection", "keep-alive");
            connection.setRequestProperty("Response-Type", "json");
            connection.setChunkedStreamingMode(0);  

        } catch (IOException e) {
            e.printStackTrace();
        }
        return connection;
    }

    // 拼接参数列表
    private String joinParams(Map<String, String> paramsMap) {
        StringBuilder stringBuilder = new StringBuilder();
        for (String key : paramsMap.keySet()) {
            stringBuilder.append(key);
            stringBuilder.append("=");
            try {
                stringBuilder.append(URLEncoder.encode(paramsMap.get(key), ENCODE_TYPE_UTF_8));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            stringBuilder.append("&");
        }
        return stringBuilder.substring(0, stringBuilder.length() - 1);
    }

}

HttpURLConnection官方接口文档


这是其中一篇文章,由于要翻墙,就直接复制过来了。
Android’s HTTP Clients –Jesse Wilson

Most network-connected Android apps will use HTTP to send and receive data. Android includes two HTTP clients: HttpURLConnection and Apache HTTP Client.
Both support HTTPS, streaming uploads and downloads, configurable timeouts, IPv6 and connection pooling.

Apache HTTP Client

DefaultHttpClient and its sibling AndroidHttpClient are extensible HTTP clients suitable for web browsers. They have large and flexible APIs. Their implementation is stable and they have few bugs.

But the large size of this API makes it difficult for us to improve it without breaking compatibility. The Android team is not actively working on Apache HTTP Client.
(虽然不错,但安卓团队人家对改这个没太大兴趣,太大太麻烦了!)

HttpURLConnection

HttpURLConnection is a general-purpose, lightweight HTTP client suitable for most applications. This class has humble beginnings, but its focused API has made it easy for us to improve steadily.
(人家说这HttpURLConnection 通用,轻量级,易维护)

Prior to Froyo, HttpURLConnection had some frustrating bugs. In particular, calling close() on a readable InputStream could poison the connection pool. Work around this by disabling connection pooling:

private void disableConnectionReuseIfNecessary() {
    // HTTP connection reuse which was buggy pre-froyo
    if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO) {
        System.setProperty("http.keepAlive", "false");
    }
}

In Gingerbread, we added transparent response compression. HttpURLConnection will automatically add this header to outgoing requests, and handle the corresponding response:

Accept-Encoding: gzip

Take advantage of this by configuring your Web server to compress responses for clients that can support it. If response compression is problematic, the class documentation shows how to disable it.

Since HTTP’s Content-Length header returns the compressed size, it is an error to use getContentLength() to size buffers for the uncompressed data. Instead, read bytes from the response until InputStream.read() returns -1.

We also made several improvements to HTTPS in Gingerbread.
HttpsURLConnection attempts to connect with Server Name Indication (SNI) which allows multiple HTTPS hosts to share an IP address. It also enables compression and session tickets. Should the connection fail, it is automatically retried without these features. This makes HttpsURLConnection efficient when connecting to up-to-date servers, without breaking compatibility with older ones.

In Ice Cream Sandwich, we are adding a response cache. With the cache installed, HTTP requests will be satisfied in one of three ways:

  1. Fully cached responses are served directly from local storage. Because no network connection needs to be made such responses are available immediately.

  2. Conditionally cached responses must have their freshness validated by the webserver. The client sends a request like “Give me /foo.png if it changed since yesterday” and the server replies with either the updated content or a 304 Not Modified status. If the content is unchanged it will not be downloaded!

  3. Uncached responses are served from the web. These responses will get stored in the response cache for later.

Use reflection to enable HTTP response caching on devices that support it. This sample code will turn on the response cache on Ice Cream Sandwich without affecting earlier releases:

private void enableHttpResponseCache() {
    try {
        long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
        File httpCacheDir = new File(getCacheDir(), "http");
        Class.forName("android.net.http.HttpResponseCache")
            .getMethod("install", File.class, long.class)
            .invoke(null, httpCacheDir, httpCacheSize);
    } catch (Exception httpResponseCacheNotAvailable) {
    }
}

You should also configure your Web server to set cache headers on its HTTP responses.

Which client is best?
Apache HTTP client has fewer bugs on Eclair and Froyo. It is the best choice for these releases.

For Gingerbread and better, HttpURLConnection is the best choice.
Its simple API and small size makes it great fit for Android.
Transparent compression and response caching reduce network use, improve speed and save battery.
New applications should use HttpURLConnection; it is where we will be spending our energy going forward.
(人家在致力于HttpURLConnection 的发展得更好,所以,你还是用吧。)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值