Which network library should you use for Android combat?

Source: Internet
Author: User
Tags connection pooling

Objective

Currently, virtually every application uses the HTTP/HTTPS protocol to transmit data as the primary transport protocol. Even if you don't use the HTTP protocol directly, there will be stacks of SDKs that include these protocols, such as analysis, crash feedback, and so on. Of course, there are also a lot of good HTTP protocol library, can be very convenient to help developers build applications, this blog post will be as far as possible to cover these points. Android developers need to consider a number of points when choosing a suitable HTTP library, such as when using Apache client or httpurlconnection, which might be considered:

    • Ability to cancel existing network requests

    • Ability to request concurrently

    • Connection pooling enables the reuse of existing socket connections

    • Local cache for the response

    • Simple asynchronous interface to avoid the main thread blocking

    • Encapsulation for the REST API

    • Re-connect Policy

    • Ability to load and transfer images efficiently

    • Support for serialization of JSON

    • Support Spdy, HTTP/2

Historical retrospect

At the earliest time Android had only two primary HTTP clients: HttpURLConnection, Apache http client. According to the content of Google's official blog, HttpURLConnection may have some bugs in earlier versions of Android:

Before the Froyo version, httpurlconnection contained some very nasty mistakes. In particular, the entire connection pool may be contaminated when the readable InputStream is closed.

Similarly, Google does not want to go to the Apache HTTP client:

The complex API design of the Apache HTTP client makes it impossible for people to use it at all, and the Android team is not able to work effectively.

For most ordinary developers, they feel they should use different clients depending on the version. For Gingerbread (2.3) and later versions, HttpURLConnection is the best choice and its API is simpler and smaller. Transparent compression and data caching can reduce network pressure, increase speed and save power. When we look at the source code of Google Volley, it can be seen that it is also based on different versions of the Android version of the different underlying network request library:

Select AllCopyput it in your notes .
if (stack == null) {    if (Build.VERSION.SDK_INT >= 9) {        stack = new HurlStack(); } else { // Prior to Gingerbread, HttpUrlConnection was unreliable. // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent)); }}

But that would be a headache for developers, who released Okhttp in 2013 to solve the split. Okhttp is directly architected with the Java socket itself without relying on other third-party libraries, so developers can use it directly in the JVM, not just Android. To simplify the speed of code migration, Okhttp also implements an interface similar to the HttpURLConnection and Apache client.

Network Library Comparison

Okhttp was supported by a huge community so that Google eventually used it as the default engine for Android 4.4 and would abandon Apache Client after 5.1. Currently Okhttp V2.5.0 supports the following features:

    • Support multiplexing for HTTP/2 and Spdy

    • Connection pooling reduces the number of concurrent connections

    • Transparent gzip encryption reduces download volume

    • Response caching avoids a large number of duplicate requests

    • Simultaneous blocking calls and asynchronous callback calls that support synchronization

The author's favorite point about okhttp is that it can show the asynchronous request better:

Select AllCopyput it in your notes .
PrivateFinal Okhttpclient client =New Okhttpclient ();PublicvoidRun()Throws Exception {Request Request =New Request.builder (). URL ("Http://publicobject.com/helloworld.txt"). Build (); Client.newcall (Request). Enqueue (new Callback () { @Override < Span class= "Hljs-keyword" >public void onfailure @Override public void onresponse (Response Response) throws ioexception {if (!response.issuccessful ()) throw new IOException ( " Unexpected code "+ response); System.out.println (Response.body (). String ()); } });} 

This is handy because often large data requests cannot be placed in the main thread of the UI. In fact, starting with Android 3.0 (Honeycomb 11), all network operations must be forced on separate threads. It was more complicated to use httpurlconnection and asynctask at that time. At the 2013 Google I/O conference, Google presented volley, an HTTP library that provides the following convenience:

    • Automatic scheduling of the network requests.

    • Multiple concurrent network connections.

    • Transparent disk and memory response caching with the standard HTTP cache coherence.

    • Support for request prioritization.

    • Cancellation the request API. You can cancel a once request, or you can set blocks or scopes of requests to cancel.

    • Ease of customization, for example, for retry and Backoff.

    • Strong ordering that makes it easy-correctly populate your UI with data fetched asynchronously from the network.

    • Debugging and tracing tools.

Volley the main architecture on the httpurlconnection, if you want to be able to crawl images or JSON data, volley has a custom abstract type imagerequest and Jsonobjectrequest, can be automatically converted to HTTP requests. At the same time, volley also has a hard-coded network connection pool size:

Select AllCopyput it in your notes .
private static final int DEFAULT_NETWORK_THREAD_POOL_SIZE = 4;

However, okhttp can customize the size of the connection pool:

Select AllCopyput it in your notes .
private int maxRequests = 64;private int maxRequestsPerHost = 5;executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), Util.threadFactory("OkHttp Dispatcher", false));

In some cases, okhttp can be better represented by the use of multiple threads. However, if the existing program has already used volley to do the top-level encapsulation, you can also use Httpstack implementation Click to preview this to use the OKHTTP request and response interface to replace HttpURLConnection.

As you can see here, Okhttp essentially customizes a set of underlying network request architectures. Currently the HTTP client has been gradually converted to support a large number of images, especially those with infinite scrolling and image transmission. At the same time, the REST API has become the industry standard, and basically every developer needs to handle a lot of standardized tasks, like JSON serialization and the interface that maps REST requests to Java. Square also proposed its own solution to both issues in the near future:

    • Retrofit- A type-safe HTTP client supports the rest interface

    • Picasso- image download and cache library for Android

Retrofit provides a bridge between Java code and the rest interface that quickly translates the HTTP API into the Java interface and automatically generates implementations with full documentation:

Select AllCopyput it in your notes .
public interface GitHubService {    @GET("/users/{user}/repos") Call<List<Repo>> listRepos(@Path("user") String user);}Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.github.com") .build();GitHubService service = retrofit.create(GitHubService.class);

In addition, Retrofit supports data conversion for JSON, XML, and protocol buffers. A comparison of Asynctask with volley and retrofit was made in another blog with the following performance comparisons:

Picture Loading Library Comparison

On the other hand, Picasso is a dedicated HTTP library for image-oriented tasks. For example, you can load a network picture into ImageView in one line of code:

Select AllCopyput it in your notes .
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);

Picasso and retrofit are the default use of okhttpclient as the underlying HTTP client, however, you can also configure your own httpurlconnection-based clients.

Glide is a very similar Picasso library, but it offers some additional features, such as GIF animations, thumbnail generation, and video.

Facebook open source their own picture loading library fresco uses their custom Android client. One of its very good features is that fresco's custom-oriented storage strategy for bitmaps avoids the limits of garbage collection at the top of the JVM heap. Fresco is allocating memory that is called the Ashmem part of Android, and it uses several methods to allow access to the Ashmem section from Java as well as C + + code, for NDK-level CPU processing. To conserve data storage and CPU consumption, fresco has three different caches: two in memory and one in internal storage.

By now, I have found that the relationship between these network libraries should be expressed in a single diagram. As you can see, the HTTP transport component exists at the bottom, interacting with all the upper-level libraries. You can choose a simple httpurlconnection or the latest okhttpclient client.

Resources
    1. Square Open Source Http://square.github.io
    2. Fresco Library http://frescolib.org
    3. Volley documentation Https://developer.android.com/training/volley
    4. Volley vs Retrofit Http://instructure.github.io/blog/2013/12/09/volley-vs-retrofit
    5. Picasso vs. Glide comparison
    6. StackOverflow thread on OkHTTP, Retrofit, volley
    7. Jake Wharton Presentations

Original: http://segmentfault.com/a/1190000003965158

Https://packetzoom.com/blog/which-android-http-library-to-use.html

Which network library should you use for Android combat?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.