The secondary encapsulation of Okhttp3 provides POST request, GET request, PATCH request, PUT request, DELETE request, upload file, download file, cancel request, Raw/Json/Gson return, background download management and other functions

1 introduction

Okhttp is a simple encapsulation of OKHTTP, with POST, GET, upload and download functions and JSON and GSON format returns.

The upgraded version of MyOkHttp has been refactored and added with many feature points, as shown below

  1. All requests are optimized for Builder mode parameter transfer (easy parameter extension)
  2. Request addHeader to add the request header
  3. Add PATCH, PUT, and DELETE request methods
  4. Added download management background, including breakpoint continuation, download queue management functions

The code has been pulled out to create a new library on GitHub, welcome Star and PR. Github.com/tsy12321/My…

2 Instructions

2.1 How Can I Add a Vm?

Add dependencies in build.gradle in the app directory

compile 'com.github.tsy12321:MyOkHttp:lastest_version'  //lastest_version See the latest version on GithubCopy the code

2.2 create MyOkHttp

Create a unique MyOkhttp instance in the project entry

MyOkHttp mMyOkhttp = new MyOkHttp();Copy the code

You can also configure OkhttpClient yourself.

OkHttpClient okHttpClient = new OkHttpClient.Builder()
                  .connectTimeout(10000L, TimeUnit.MILLISECONDS)
                  .readTimeout(10000L, TimeUnit.MILLISECONDS)
                  // Other configurations
                 .build();

MyOkHttp mMyOkhttp = new MyOkHttp(okHttpClient);Copy the code

2.3 Call Method

The whole call takes the form of a chain call. Easy to expand later.

2.4 Request Type

Now there are Get, Post, Patch, Put, Delete, Upload, Download request methods

2.5 Method for Adding Parameters

Parameters can be added individually using addParam or all at once using Params

2.6 Adding headers

You can add parameters one by one using addHeader, or you can add them all at once using headers

2.7 Callback format

There are now several callback formats:

  1. Raw Raw data RawResponseHandler
  2. Json JsonResponseHandler
  3. Gson GsonResponseHandler

2.8 Invocation Example

2.8.1 POST Request + Json Callback Example

String url = "http://192.168.2.135/myokhttp/post.php";

Map<String, String> params = new HashMap<>();
params.put("name"."tsy");
params.put("age"."24");

mMyOkhttp.post()
        .url(url)
        .params(params)
        .tag(this)
        .enqueue(new JsonResponseHandler() {
            @Override
            public void onSuccess(int statusCode, JSONObject response) {
                Log.d(TAG, "doPost onSuccess:" + response);
            }

            @Override
            public void onFailure(int statusCode, String error_msg) {
                Log.d(TAG, "doPost onFailure:"+ error_msg); }});Copy the code

2.8.2 GET Request + Raw Callback Example

String url = "http://192.168.2.135/myokhttp/get.php";

mMyOkhttp.get()
        .url(url)
        .addParam("name"."tsy")
        .addParam("id"."5")
        .tag(this)
        .enqueue(new RawResponseHandler() {
            @Override
            public void onSuccess(int statusCode, String response) {
                Log.d(TAG, "doGet onSuccess:" + response);
            }

            @Override
            public void onFailure(int statusCode, String error_msg) {
                Log.d(TAG, "doGet onFailure:"+ error_msg); }});Copy the code

2.8.3 Patch Request + Json Callback Example

String url = "http://192.168.2.135/myokhttp/patch.php/id/5/name/tsy";

mMyOkhttp.patch()
        .url(url)
        .tag(this)
        .enqueue(new JsonResponseHandler() {
            @Override
            public void onSuccess(int statusCode, JSONObject response) {
                Log.d(TAG, "doPatch onSuccess:" + response);
            }

            @Override
            public void onFailure(int statusCode, String error_msg) {
                Log.d(TAG, "doPatch onFailure:"+ error_msg); }});Copy the code

2.8.4 Uploading a File + Gson Callback Example

String url = "http://192.168.2.135/myokhttp/upload.php";

mMyOkhttp.upload()
        .url(url)
        .addParam("name"."tsy")
        .addFile("avatar".new File(Environment.getExternalStorageDirectory()
                        + "/ahome/sasas.jpg"))        // Upload an existing File
//.addfile ("avatar2", "asdsda.png", byteContents) // Upload File bytes directly
        .tag(this)
        .enqueue(new GsonResponseHandler<UploadModel>() {
            @Override
            public void onFailure(int statusCode, String error_msg) {
                Log.d(TAG, "doUpload onFailure:" + error_msg);
            }

            @Override
            public void onProgress(long currentBytes, long totalBytes) {
                Log.d(TAG, "doUpload onProgress:" + currentBytes + "/" + totalBytes);
            }

            @Override
            public void onSuccess(int statusCode, UploadModel response) {
                Log.d(TAG, "doUpload onSuccess:" + response.ret + ""+ response.msg); }});Copy the code

2.8.5 Downloading files

String url = "http://192.168.2.135/myokhttp/head.jpg";

mMyOkhttp.download()
        .url(url)
        .filePath(Environment.getExternalStorageDirectory() + "/ahome/a.jpg")
        .tag(this)
        .enqueue(new DownloadResponseHandler() {
            @Override
            public void onStart(long totalBytes) {
                Log.d(TAG, "doDownload onStart");
            }

            @Override
            public void onFinish(File downloadFile) {
                Log.d(TAG, "doDownload onFinish:");
            }

            @Override
            public void onProgress(long currentBytes, long totalBytes) {
                Log.d(TAG, "doDownload onProgress:" + currentBytes + "/" + totalBytes);
            }

            @Override
            public void onFailure(String error_msg) {
                Log.d(TAG, "doDownload onFailure:"+ error_msg); }});Copy the code

2.9 to cancel the request, advice on BaseActivity, BaseFragment onDestroy)

mMyOkhttp.cancel(this);     // Tag is the tag passed in the previous request. It is recommended to pass the page directly as objectCopy the code

2.10 Download Management

The core logic of download management is realized, including adding download task, starting task, suspending task, deleting task, waiting task download, download progress and status monitoring. Rely on MyOkhttp

2.10.1 implementation AbstractDownloadMgr

AbstractDownloadMgr is created in the project and implements local persistent saving of download task status and progress. (AbstractDownloadMgr is only responsible for storing all tasks in memory, requiring the project to implement local persistence storage and task recovery after re-entering App, etc.)

Example:

AbstractDownloadMgr * Created by tsy on 2016/11/24. */

public class DownloadMgr extends AbstractDownloadMgr {

    private DownloadMgr(Builder builder) {
        super(builder);
    }

    /** * Initially enter app to restore all unfinished tasks */
    @Override
    public void resumeTasks(a) {
        if(DEBUG) {
            Log.i(TAG, "start resumeTasks");
        }

        // Get all unfinished tasks (completed ones don't need to be added)
        DownloadContract.Interactor downloadInteractor = new DownloadInteractor();
        ArrayList<Task> tasks = downloadInteractor.parseTask(downloadInteractor.getAllUnfinishedDownloadTasks());

        // Add the task to the download management queue
        if(tasks ! =null && tasks.size() > 0) {
            for(int i = 0; i < tasks.size(); i ++) {
                Task task = tasks.get(i);
                task.setDefaultStatus(DEFAULT_TASK_STATUS_PAUSE);       // All tasks are initially set to pauseaddTask(tasks.get(i)); } downloadInteractor.pauseAllTask(); }}/** * Save progress *@param taskId taskId
     * @paramCurrentBytes Bytes * that have been downloaded@paramTotalBytes totalBytes */
    @Override
    protected void saveProgress(String taskId, long currentBytes, long totalBytes) {
        DownloadContract.Interactor downloadInteractor = new DownloadInteractor();
        downloadInteractor.updateProgress(taskId, currentBytes, totalBytes);
    }

    /** * Download task started *@param taskId task id
     */
    @Override
    protected void onTaskStart(String taskId) {
        DownloadContract.Interactor downloadInteractor = new DownloadInteractor();
        downloadInteractor.startTask(taskId);
    }

    /** * Download task paused *@param taskId task id
     */
    @Override
    protected void onTaskPause(String taskId) {
        DownloadContract.Interactor downloadInteractor = new DownloadInteractor();
        downloadInteractor.pauseTask(taskId);
    }

    /** * Download task completed *@param taskId task id
     */
    @Override
    protected void onTaskFinish(String taskId) {
        DownloadContract.Interactor downloadInteractor = new DownloadInteractor();
        downloadInteractor.finishTask(taskId);
    }

    /** * Failed to download the task@param taskId task id
     */
    @Override
    protected void onTaskFail(String taskId) {
        // Failure is set to pause to allow the user to try again to start
        DownloadContract.Interactor downloadInteractor = new DownloadInteractor();
        downloadInteractor.pauseTask(taskId);
    }

    / / implementation Builder
    public static class Builder extends AbstractDownloadMgr.Builder {

        @Override
        public AbstractDownloadMgr build(a) {
            return new DownloadMgr(this); }}}Copy the code

2.10.2 Initialize and customize the unique instance DownloadMgr at the beginning of the project

mDownloadMgr = (DownloadMgr) new DownloadMgr.Builder()
                .myOkHttp(mMyOkhttp)
                .maxDownloadIngNum(5)       // Set the maximum number of simultaneous downloads (default 5 is not set)
                .saveProgressBytes(50 * 1024)  // Set saveProgress to be triggered every 50KB (not too frequently in onProgress each time). Do not set default 50KB
                .build();Copy the code

2.10.3 Restoring All Unfinished Tasks of Local Storage

mDownloadMgr.resumeTasks();Copy the code

2.10.4 Creating a Download Task

DownloadMgr.Task task = new DownloadMgr.Task();
task.setTaskId(mDownloadMgr.genTaskId());       // Generate a taskId
task.setUrl("xxxxx");   // Download the address
task.setFilePath("xxxxxxx");    // Save the file after downloading
task.setCompleteBytes(1234L);       // Set completed bytes (to be added when a recovery task is added, if this field is not required for a newly added task)
task.setDefaultStatus(DownloadMgr.DEFAULT_TASK_STATUS_START);       // Task start Status If the default value is not set, the task starts automatically after being added

mDownloadMgr.addTask(task);Copy the code

2.10.5 Starting to Suspend tasks

mDownloadMgr.startTask("taskId");

mDownloadMgr.pauseTask("taskId");Copy the code

2.10.6 Adding download listening on the page

PS: Do not use anonymous classes, they will cause memory leaks. Initialize listener on onStart or onResume and destroy listener on onStop or onPause

@Override
public void onResume(a) {
    super.onResume();

    // Add a listener every time the page is displayed
    mDownloadTaskListener = new DownloadTaskListener() {
        @Override
        public void onStart(String taskId, long completeBytes, long totalBytes) {
            // Start downloading
        }

        @Override
        public void onProgress(String taskId, long currentBytes, long totalBytes) {
            // Download progress

            // It is recommended to use handler to delay updating the download progress or refresh it too frequently
            if(! mMyHandler.hasMessages(MSG_DELAY_NOTIFICAION)) { Message message =new Message();
                message.what = MSG_DELAY_NOTIFICAION;
                mMyHandler.sendMessageDelayed(message, 300); }}@Override
        public void onPause(String taskId, long currentBytes, long totalBytes) {
            // Download paused
        }

        @Override
        public void onFinish(String taskId, File file) {
            // Download complete
        }

        @Override
        public void onFailure(String taskId, String error_msg) {
            // Download failed}};// Join the listener
    mDownloadMgr.addListener(mDownloadTaskListener);
}

@Override
public void onPause(a) {

    // Release listeners to prevent memory leaks
    mDownloadMgr.removeListener(mDownloadTaskListener);
    mDownloadTaskListener = null;

    super.onPause();
}Copy the code

3 the end

Specific implementation in the code has a small Demo. Again attached is Github address: github.com/tsy12321/My…


The 2017-01-06 update

1 Add local persistent cookie => PersistentCookieJar

Set a cookie.

// Enable cookie
ClearableCookieJar cookieJar =
        new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(getApplicationContext()));
OkHttpClient okHttpClient = new OkHttpClient.Builder()
        .cookieJar(cookieJar)
        .build();
mMyOkHttp = new MyOkHttp(okHttpClient);Copy the code

2 POST Adds a JSON parameter request

String url = "http://192.168.2.135/myokhttp/post_json.php";

JSONObject jsonObject = new JSONObject();

try {
    jsonObject.put("name"."tsy");
    jsonObject.put("age".24);
    jsonObject.put("type"."json");
} catch (JSONException e) {
    e.printStackTrace();
}

mMyOkhttp.post()
        .url(url)
        .jsonParams(jsonObject.toString())          // jsonParams is preferred if it does not coexist with params
        .tag(this)
        .enqueue(new JsonResponseHandler() {
            @Override
            public void onSuccess(int statusCode, JSONObject response) {
                Log.d(TAG, "doPostJSON onSuccess JSONObject:" + response);
            }

            @Override
            public void onSuccess(int statusCode, JSONArray response) {
                Log.d(TAG, "doPostJSON onSuccess JSONArray:" + response);
            }

            @Override
            public void onFailure(int statusCode, String error_msg) {
                Log.d(TAG, "doPostJSON onFailure:"+ error_msg); }});Copy the code