Encapsulation of OkHttp (parameters are all submitted using Json)

Posted by KyleVA on Sat, 18 May 2019 09:54:33 +0200

OkHttp believes it's not unfamiliar. Android is a useful framework for web requests. GitHub has more than 2 weeks of Start s on it and Square is one of Jake Wharton's masterpieces (Jake Wharton left Square to join Google), where he worships God for three seconds...

I encapsulated OkHttp twice as needed for the project because, in consultation with the backstage buddies, all the parameters were transferred to Json and passed to the server.When uploading pictures, convert them to Base64 strings and upload them to the server in Json format as well.

This is the third-party dependency I use:

compile 'com.squareup.okhttp3:okhttp:3.8.1'  //OkHttp dependency, may not be the latest version, can go to GitHub to find the latest OkHttp dependency  

compile 'id.zelory:compressor:2.0.0'  //Picture compression, compression efficiency and speed are good
  • 1
  • 2
  • 3

First, create a single class for OkHttp.When using OkHttp, it is best to ensure that there is only one OkHttpClient object globally, which makes it easy to manage and configure the timeouts, caches, etc. of network requests for the entire application.If there is a particular network request that we need to process, we can also clone an OkHttpClient object to process separately.

public class OkHttpClientInstance {

    public static OkHttpClient instance;

    private OkHttpClientInstance() {}

    public static OkHttpClient getInstance() {
        if (instance == null) {
            synchronized (OkHttpClientInstance.class) {
                if (instance == null) {
                    //Network request timeout configured
                    instance = new OkHttpClient().newBuilder()
                            .connectTimeout(10, TimeUnit.SECONDS)
                            .readTimeout(10, TimeUnit.SECONDS)
                            .writeTimeout(10, TimeUnit.SECONDS)
                            .build();

                }
            }
        }
        return instance;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

Create Network Request Class Network

public class Network {

    //context
    private Context      mContext;
    //Requested url
    private String       mUrl;
    //OkHttpClient object from a single class
    private OkHttpClient mClient;
    //Gson for parsing data returned by the server
    private Gson         mGson;
    private Handler      mHandler;
    //Token string returned after login
    private String       mToken;

    public Network(Context context, String url) {
        this.mContext = context;
        this.mUrl = url;
        mClient = OkHttpClientInstance.getInstance();
        mGson = new Gson();
        mHandler = new Handler();
        //Get Token as a global variable when you enter the program
        mToken = SPUtil.getString(context, SPUtil.LOGIN_TOKEN, "");
    }

    /**
     * Perform a normal post request with all parameters turned into json
     *
     * @param map  Incoming parameter set
     * @param netCallBack  Callback interface
     */
    public void performPost(Map<Object, Object> map, final NetCallBack netCallBack) {
        String params = mGson.toJson(map);
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, params);

        final Request request = new Request.Builder()
                .url(mUrl)
                .addHeader("Authorization", "Bearer" + mToken)
                .post(body)
                .build();
        mClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                doFailure(netCallBack);
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                doResponse(response, netCallBack);
            }
        });
    }


    /**
     * post Upload pictures, all into json upload
     *
     * @param params  Set of parameters
     * @param picturePathList  Path Collection for Pictures
     * @param netCallBack  Callback interface
     */
    public void upLoadPicture(Map<Object, Object> params, List<String> picturePathList, final NetCallBack netCallBack) {

        List<PictureFileBean> fileList = new ArrayList<>();

        //Processing Pictures
        for (int i = 0; i < picturePathList.size(); i++) {
            File file = new File(picturePathList.get(i));
            PictureFileBean fileBean = new PictureFileBean();
            try {
                //Compressed Picture
                File compressedFile = new Compressor(mContext).compressToFile(file);
                //Convert Picture to base64
                String base64String = ImageToBase64.GetImageStr(compressedFile);
                //Stitch Picture Collection
                fileBean.setPicFile(base64String);
                fileBean.setPicType("JPEG");
                fileList.add(fileBean);

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

        params.put("file", fileList);
        String json = mGson.toJson(params);
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody requestBody = RequestBody.create(JSON, json);

        final Request request = new Request.Builder()
                .url(mUrl)
                .addHeader("Authorization", "Bearer" + mToken)
                .post(requestBody)
                .build();


        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mClient.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        doFailure(netCallBack);
                    }

                    @Override
                    public void onResponse(Call call, final Response response) throws IOException {
                        doResponse(response, netCallBack);
                    }
                });
            }
        }, 200);
    }

     /**
     * Processing Failure
     *
     * @param netCallBack
     */
    private void doFailure(final NetCallBack netCallBack) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                netCallBack.onNetFailure();
            }
        });
    }

    /**
     * Processing Successful
     *
     * @param response
     * @param netCallBack
     * @throws IOException
     */
    private void doResponse(Response response, final NetCallBack netCallBack) throws IOException {
        final String result = response.body().string();
        if (!TextUtils.isEmpty(result)) {
            try {
                JSONObject jsonObject = new JSONObject(result);
                String success = jsonObject.getString("success");

                if ("true".equals(success)) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            netCallBack.onSuccess(result);
                        }
                    });
                } else if ("false".equals(success)) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            netCallBack.onError(result);
                        }
                    });
                }
            } catch (JSONException e) {
                e.printStackTrace();
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        //Server returned error
                        netCallBack.onError(result);
                    }
                });
            }
        }
    }


   /**
     * Callback interface
     */
    public interface NetCallBack {

        //Network request failed, no connection
        void onNetFailure();

        //Network request succeeded
        void onSuccess(String result);

        //Network request succeeded, background server error
        void onError(String result, String errorMessage);

    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • I created an internal interface class to handle callbacks to the results of network requests.There are three ways to do this:

    • The onNetFailure() method is used to handle network requests that fail without networking;
    • The onSuccess() method is used to handle callbacks that are successful for network requests;
    • The onError() method is used to handle situations in which the background server returns an error, and it is often combined with an error code to more specifically handle the result.
  • Picture to Base64 Method

public class ImageToBase64 {

    /**
     * Picture to base64
     * @param file
     * @return
     */
    public static String GetImageStr(File file) {
        Bitmap bitmap = BitmapFactory.decodeFile(file.getPath());
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);//Parameter 100 means no compression
        byte[] bytes = bos.toByteArray();
        try {
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Base64.encodeToString(bytes, Base64.DEFAULT);
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

With regard to calls, you can call Network Network Layer methods directly from within Activity, but I don't recommend you do so.Based on the principle of high cohesion and low coupling, a second class can be written that encapsulates business-specific request methods and provides them to Activity calls.

public class ActivityNet {

    private Context mContext;

    public AbnormalHandleActivityNet(Context context) {
        mContext = context;
    }

    /**
     * Confirm Handling Exception Click Events
     *
     * @param guid
     * @param abnormalCount
     * @param abnormalTypePosition
     * @param abnormalRemark
     * @param parentGuid
     * @param picturePathList
     */
    public void btnConfirmHandle(String guid, String abnormalCount, int abnormalTypePosition, String abnormalRemark, String parentGuid, ArrayList<String> picturePathList, Network.NetCallBack netCallBack) {
        String url = UrlUtil.getUrl("tms.app.order.backed.backExSubmit");
        Map<Object, Object> params = new HashMap<>();
        params.put("guid", guid);
        params.put("exceptionQty", abnormalCount);
        params.put("exceptionType", abnormalTypePosition);
        params.put("exceptionMemo", abnormalRemark);
        params.put("parentGuid", parentGuid);
        Network network = new Network(mContext, url);
        network.upLoadPicture(params, picturePathList, netCallBack);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

This is a complex invocation method that requires both uploading parameters and uploading pictures.Parameters are added to the Map collection as key-value pairs, and the meaning of each key is discussed with the background buddies, which are contained in the interface document.(
The picturePathList is a collection of picture paths.We may upload multiple pictures at the same time, get the paths of multiple pictures, and build a collection.(
This class contains business-specific network request methods, which we call directly in Activity.Activity can process results and make corresponding UI updates by implementing the Network.NetCallBack interface.

Topics: network JSON OkHttp github