Summary of Android Common Network Framework

Keywords: OkHttp network Retrofit Android

Native Network Request HttpUrlConnection

Its API is simple and small, so it is very suitable for Android projects. Compression and caching mechanism can effectively reduce network access traffic, and also play a major role in improving speed and saving power.

usage

  1. First, we need to get an instance of HttpURLConnection. Generally, we need to new out a URL object and pass in the target network address. We can get an instance of HttpURLConnection by calling openConnection().
  2. After the example is obtained. We need to set up the method of http request. Here we mainly study get and post. By default, get method is used. Get is generally used to get data from the server, post is generally used to submit data to the server, setting the request method using the function setRequestMethod("POST").
  3. In addition, there are some restrictions on requests, such as connection timeout time, which can be set by setConnect Timeout.
  4. Get the input stream returned by the server and use the getInputStream method to get it.
  5. Read the content and process it
  6. Close the connection and close the current connection by calling the disconnect method.
    Don't forget to add permissions during use
<uses-permission android:name="android.permission.INTERNET"/>

Prevent network requests from getting stuck:

  • Call connection.disconnect(); collocate empty objects
  • Set request timeout

GET Request Implementation

public String get(String urlPath) {
        HttpURLConnection connection = null;
        InputStream is = null;
        try {
            URL url = new URL(urlPath);
            //Get the URL object
            connection = (HttpURLConnection) url.openConnection();
            //Get the HttpURLConnection object
            connection.setRequestMethod("GET");
            // The default is GET.
            connection.setUseCaches(false);
            //No caching
            connection.setConnectTimeout(10000);
            //Setting timeout time
            connection.setReadTimeout(10000);
            //Setting the read timeout time
            connection.setDoInput(true);
            //Set whether to read from httpUrlConnection, true by default;
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                //Is the corresponding code 200
                is = connection.getInputStream();
                //Get the input stream
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                //Wrap byte stream as character stream
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                return response.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
                connection = null;
            }
            if (is != null) {
                try {
                    is.close();
                    is = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

I. Volley

Volley is a small and delicate asynchronous request library launched by google's official 2013 I/O conference. The framework encapsulates extensibility, supports HttpClient, HttpUrlConnection, and even OkHttp.

Advantage:

  • Suitable for small and frequent requests, usually combined with other frameworks, such as volley+okhttp.

  • Extensibility, secondary packaging

  • Linkage with Activity and Life Cycle (Canceling all network requests at the end of activity)

Disadvantages:

The performance of downloading large files is not good, and uploading large files is not supported.

GET request

private void get(){
        RequestQueue queue= Volley.newRequestQueue(getApplicationContext());
        String url="http://121.41.119.107/test/index.php";
        StringRequest request=new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.d("TAG",response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        queue.add(request);
    }

Two, OkHttp

Advantage:

  • Support SPDY, share the same Socket to process all requests from the same server
  • Seamless support for GZIP to reduce data traffic
  • If there are multiple IP addresses on the server side, OkHttp will attempt to connect to other addresses when the first address connection fails.

Close the request: call.cancel() to cancel the request

GET request

private String get(String url) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

III. Retrofit

Retrofit is a default RESTful network request framework based on OkHttp package produced by Square. RESTful can be said to be a popular style of api design, not a standard. Retrofit encapsulation can be said to be very powerful, which involves a bunch of design patterns, can use different http clients, although the default is http, you can use different Json Coonverter to serialize data, while providing support for RxJava, using Retrofit+OkHttp+RxJava+Dagger2 can be said to be a relatively popular framework, but relatively high threshold.

Note: The premise of using Retrofit is that the server-side code follows the RESTful specification!!!!

Close the request: call.cancel() to cancel the request

Advantage:

  • Very efficient
  • You can directly convert the results to Java classes
  • Mainly used with RxJava
  • The transport layer uses OkHttp by default

The biggest advantage: Request response time is much faster or even twice less than volley and Okhttp

Posted by mastercool on Mon, 01 Apr 2019 07:54:29 -0700