Introduction to the

At present, OKHttp is the most commonly used framework for calling network requests on Android, which is also frequently used in current projects. What are the features of OKHTTP? Here are the features of OKHTTP:

  1. Support for HTTP/2, which supports concurrency over a single TCP connection by using multiplexing technology to send or receive data by sending multiple requests at once on a single connection;
  2. Connection pool multiplexing can also greatly reduce latency if HTTP/2 is not available;
  3. Transparent Gzip processing reduces the size of communication data
  4. Response caching completely eliminates duplicate requests in the network
  5. Use Okio to simplify data access and storage and improve performance
  6. If your server is configured with multiple IP addresses, when the first IP fails to connect, OkHttp will automatically try the next IP
  7. OkHttp also handles proxy server issues and SSL handshake failures;

Website address: square. Making. IO/okhttp/want to learn more about HTTP / 2, you can refer to: www.jianshu.com/p/828a29bce…

configuration

  1. Add the OKHttp dependency
Implementation 'com. Squareup. Okhttp3: okhttp: 3.12.3'Copy the code
  1. Add network permissions if file read and write permissions are required
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Copy the code

Now you’re happy to start developing using OKhttp.

Create OkHttpClient

OKhttpclient through builder construction, construction involves a lot of configuration items, this brief to some of the configuration items to do, will be followed by some important configuration items to do a special topic. Configuration items in actual projects can be configured based on project requirements.

    OkHttpClient.Builder builder = new OkHttpClient.Builder();

    // Cache directory
    File externalCacheDir = context.getExternalCacheDir();
    if(externalCacheDir ! =null) {
        Cache okHttpCache = new Cache(new File(externalCacheDir,
                "HttpCache"), 30 * 1024 * 1024);
        builder.cache(okHttpCache);
    }

    The connection timeout is applied when the TCP SOCKET is connected to the destination host. The default value is 10 seconds
    builder.connectTimeout(30, TimeUnit.SECONDS);
    // Read timeout, including TCP SOCKET and Source and Response read I/O operations, default 10s
    builder.readTimeout(20, TimeUnit.SECONDS);
    // Write timeout duration, which refers to the I/O write operation. The default value is 10 seconds
    builder.writeTimeout(20, TimeUnit.SECONDS);
    // Timeout for the entire invocation period, including DNS resolution, linking, writing request body, server processing, and reading response results
    builder.callTimeout(120, TimeUnit.SECONDS);

    // For a single client to listen on all parsing events, can be used to calculate parsing time
    builder.eventListener(EventListener.NONE);

    // Add interceptors. Some interceptors are already added inside the framework by default. The interceptors added through the interface are at the head of the list
    builder.addInterceptor(new LogInterceptor());
    // Add a network interceptor, which can manipulate redirection and failed reconnection returns, and monitor all network data
    builder.addNetworkInterceptor(new NetworkInterceptor());

    // During the handshake, if the URL host name does not match the server's identity host name, the validation mechanism can call back the implementer of this interface to determine whether the connection should be allowed.
    // Return false to disallow the link, thoughtless return true is unsafe
    builder.hostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true; }});Authenticator.none by default
// builder.authenticator(Authenticator.NONE);

// The connection pool has 5 free connections by default and lasts 5 minutes
// builder.connectionPool(new ConnectionPool());

// Customize CookieJar, default cookiejar.no_cookies
// builder.cookieJar(CookieJar.NO_COOKIES);

// Scheduling policy. By default, the maximum number of concurrent requests is 64, but the maximum number of requests per domain name is 5
// builder.dispatcher(new Dispatcher());

// Configure the certificate authentication policy
// builder.sslSocketFactory();

      OkHttpClient  client = builder.build();
Copy the code

The most common configuration items are

  1. The path of the cache file and the size of the cache
  2. Timeout for linking, reading, and writing network requests
  3. Interceptors, which are most commonly used by OKHTTP, can be used to handle functions including retry, caching, log printing, and so on
  4. Domain name and certificate verification
  5. Connectors and concurrent scheduling strategies

Synchronizing GET requests

public void synGet(String url) {
        
        // First, build HttpUrl
        HttpUrl.Builder builder = null;
        try {
            HttpUrl httpUrl = HttpUrl.parse(url);
            if(httpUrl ! =null){ builder = httpUrl.newBuilder(); }}catch (IllegalArgumentException e) {
            e.printStackTrace();
        }

        if (builder == null) {
            return;
        }
        builder.addQueryParameter("key"."value");

        // Create the Request object
        Request request = new Request.Builder()
                // Request an address
                .url(httpUrl)
                // Get request. The default is GET request
                .get()
                // Add a request header. One key corresponds to multiple values, which can be customized
                .addHeader("key"."value")
                .addHeader("key"."value1")
                // Request headers, one-to-one, such as content-type, accept-encoding, etc
                .header("key1"."value1")
                // Cache policy, currently used to enforce network requests
                .cacheControl(CacheControl.FORCE_NETWORK)
                // Cache policy
                .build();

        try {
            // Step 3, start the synchronization request
            Response response = client
                    .newCall(request)
                    .execute();

            // Step 4, parse the response result
            ResponseBody body = response.body();
            if(body ! =null) { Log.d(TAG, body.string()); }}catch(IOException e) { e.printStackTrace(); }}Copy the code

A synchronous GET request blocks the current thread until the result is returned. The request is roughly divided into four steps:

  1. Build HttpUrl, of course this step is not required, you can pass in the address directly
  2. The second step is to build the Request object, which can set the Request header, cache policy and Request mode
  3. Third, start the synchronization request
  4. Parsing response results

Note: Synchronous GET requests must be made in child threads, otherwise the application will throw exceptions.

Asynchronous GET request

The steps in the asynchronous request mode are basically the same as those in the previous two steps. The main way of initiating the request is changed, and the results are returned through the callback. There is no limit to the thread of the request.


// First, build HttpUrl
// Create the Request object
// Step 3, start the asynchronous request
client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {}@Override
            public void onResponse(Call call, Response response) throws IOException {
                // Step 4, parse the response result
                ResponseBody body = response.body();
                if(body ! =null) { Log.d(TAG, body.string()); }}});Copy the code

Synchronizing POST requests

public void synPost(String url) {
    // First, build HttpUrl
    HttpUrl.Builder builder = null;
    try {
        HttpUrl httpUrl = HttpUrl.parse(url);
        if(httpUrl ! =null) { builder = httpUrl.newBuilder(); }}catch (IllegalArgumentException e) {
        e.printStackTrace();
    }
    if (builder == null) {
        return;
    }

    // Step 2, build the RequestBody
    MediaType mediaType = MediaType.parse("application/json; charset=UTF-8");
    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject.put("key1"."value1");
        jsonObject.put("key2"."value2");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    RequestBody requestBody = RequestBody.create(mediaType, jsonObject.toString());
    // Create the Request object
    Request request = new Request.Builder()
            .url(builder.build())
            .post(requestBody)
            .build();
    
    // Step 4, start the synchronous POST request
    try {
        Response response = client.newCall(request).execute();
        // Step 5, parse the request result
        ResponseBody body = response.body();
        if(body ! =null) { Log.d(TAG, body.string()); }}catch(IOException e) { e.printStackTrace(); }}Copy the code

Unlike get requests, POST requests need to build a RequestBody, which is carried along with the request.

Asynchronous POST request

public void asynPost(String url) {
        // First, build HttpUrl
        // Step 2, build the RequestBody
        // Create the Request object
        Request request = new Request.Builder()
                .url(builder.build())
                .post(requestBody)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {}@Override
            public void onResponse(Call call, Response response) throws IOException {
                ResponseBody body = response.body();
                if(body ! =null) { Log.d(TAG, body.string()); }}}); }Copy the code

Upload a file

    // First, build HttpUrl
    // Step 2, build the RequestBody
    MediaType mediaType = MediaType.parse("multipart/form-data; charset=utf-8");
    RequestBody requestBody = RequestBody.create(mediaType, file);
	// Build the MultipartBody
    MultipartBody body = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            // Add multiple RequestBodies here for multiple file uploads
            .addFormDataPart("file", file.getName(), requestBody)
            .build();

    // Create the Request object
    Request request = new Request.Builder()
            .url(builder.build())
            .post(body)
            .build();
	// Create a Request object
    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {}@Override
        public void onResponse(Call call, Response response) throws IOException {
            ResponseBody body = response.body();
            if(body ! =null) { Log.d(TAG, body.string()); }}});Copy the code

The form submission

	// Step 2, build the RequestBody
    FormBody formBody = new FormBody.Builder()
            .add("key1"."value1")
            .add("key2"."value2")
            .build();

    // Create the Request object
    Request request = new Request.Builder()
            .url(builder.build())
            .post(formBody)
            .build();

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {}@Override
        public void onResponse(Call call, Response response) throws IOException {
            ResponseBody body = response.body();
            if(body ! =null) { Log.d(TAG, body.string()); }}});Copy the code