1. Android articles-use okhttp to request the background interface package tool class to facilitate the call

problem:

How does the android side initiate a request to call the back-end data interface to achieve the effect of interaction.

Note: Sometimes when we need to have a conversation with the background, we need to carry cookie information. At this time, we need the getCookie method to carry the cookie information. At this time, we need to save it locally when logging in. We will have this in the next article. Detailed Description.

1: First, we need to import related okhttp dependencies in build.gradle

        implementation 'com.squareup.okhttp3:okhttp:3.10.0'  //okhttp
        implementation 'com.alibaba:fastjson:1.2.56'     //阿里json处理

2: Then you can use okhttp to call, the code is simply encapsulated here, the content is as follows:

(1). This is the requested tool class

package com.zjxf.utils;

import android.content.Context;

import com.alibaba.fastjson.JSONObject;
import com.zjxf.cache.CacheKeys;
import com.zjxf.common.SysConst;

import io.netty.util.internal.StringUtil;
import okhttp3.CacheControl;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * created with IntelliJ IDEA
 *
 * @author: create by limu
 * Date: 2019/11/12
 * Time:9:39
 */
public class RequestUtils {

    public static final MediaType FORM_CONTENT_TYPE = MediaType.parse("application/json;charset=utf-8");

    private static final byte[] LOCKER = new byte[0];

    private static RequestUtils mInstance;

    /**
     * post请求不传递参数
     *
     * @param url      请求地址
     * @param callback 执行函数
     */
    public void postEmpty(Context context, String url, final Callback callback) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(splicingUrl(url)).post(okhttp3.internal.Util.EMPTY_REQUEST)
                .addHeader("Cookie", getCookie(context))
                .cacheControl(CacheControl.FORCE_NETWORK)
                .build();
        client.newCall(request).enqueue(callback);
    }

    /**
     * get请求不传递参数
     *
     * @param url      请求地址
     * @param callback 执行函数
     */
    public void getEmpty(Context context, String url, final Callback callback) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url).get()
                .addHeader("Cookie", getCookie(context))
                .cacheControl(CacheControl.FORCE_NETWORK)
                .build();
        client.newCall(request).enqueue(callback);
    }

    /**
     * 发送json数据
     *
     * @param url       请求地址
     * @param paramJson 发送json数据
     * @param callback  执行函数
     */
    public void postJson(String url, JSONObject paramJson, final Callback callback) {
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = OkHttpUtils.setJSONBody(paramJson.toJSONString());
        Request request = new Request.Builder()
                .url(splicingUrl(url)).post(requestBody)
                .cacheControl(CacheControl.FORCE_NETWORK)
                .build();
        client.newCall(request).enqueue(callback);
    }


    /**
     * 发送表单数据
     *
     * @param url       请求地址
     * @param paramJson 请求参数
     * @param callback  执行函数
     */
    public void postForm(Context context, String url, JSONObject paramJson, final Callback callback) {
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = OkHttpUtils.setFormBody(paramJson);
        Request request = new Request.Builder()
                .url(splicingUrl(url)).post(requestBody)
                .addHeader("Cookie", getCookie(context))
                .cacheControl(CacheControl.FORCE_NETWORK)
                .build();
        client.newCall(request).enqueue(callback);
    }


    /**
     * 发送表单数据
     *
     * @param url       请求地址
     * @param paramJson 请求参数
     * @param callback  执行函数
     */
    public void postFormByLogin(Context context, String url, JSONObject paramJson, final Callback callback) {
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = OkHttpUtils.setFormBody(paramJson);
        Request request = new Request.Builder()
                .url(splicingUrl(url)).post(requestBody)
                .cacheControl(CacheControl.FORCE_NETWORK)
                .build();
        client.newCall(request).enqueue(callback);
    }

    /**
     * 单例模式获取RequestUtils
     *
     * @return RequestUtils
     */
    public static RequestUtils getInstance() {
        if (mInstance == null) {
            synchronized (LOCKER) {
                if (mInstance == null) {
                    mInstance = new RequestUtils();
                }
            }
        }
        return mInstance;
    }

    /**
     * 组合请求地址
     *
     * @param url 映射地址
     * @return 请求地址
     */
    private String splicingUrl(String url) {
        return SysConst.REMOTE_URL + url;
    }


    /**
     * 获取登录信息
     *
     * @param context 上下文对象
     * @return String
     */
    public String getCookie(Context context) {
        String sessionId = SharedPrefUtils.getInstance().getStrBykey(CacheKeys.LOGIN_SESSION_Id, StringUtil.EMPTY_STRING);
        if (sessionId.equals(StringUtil.EMPTY_STRING)) {
            return SysConst.EMPTY;
        } else {
            return sessionId;
        }
    }

}

(2). CacheKeys is a constant for the key used to cache the login cookie 

package com.zjxf.cache;

/**
 * created with IntelliJ IDEA
 *
 * @author: create by limu
 * Date: 2020/4/9
 * Time:10:31
 */
public class CacheKeys {

    public final static String LOGIN_USERNAME = "login_user_name:";
    public final static String THIS_SCHOOL_NAME = "this_school_name:";
    public final static String LOGIN_SESSION_Id = "login_session_id:";


}

 (3). SysConst is a management of the system constant class 

package com.zjxf.common;


/**
 * created with IntelliJ IDEA
 * <p>
 * 系统常量类
 * <p>
 * Date: 2020/2/12
 *
 * @author: create by limu
 * Time:16:23
 */
public class SysConst {

    public static final String REMOTE_URL = "http://39.100.143.199:8631";    //远程请求地址 后缀不加斜杆
}

3. Usage

 JSONObject paramJson = new JSONObject();
        paramJson.put("bankId", bankId);

        RequestUtils.getInstance().postForm(AnswerActivity.this, ResourceManagerUrlConstants.PSY_APP_FIND_BY_TOPICS, paramJson, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> ToastUtils.showToastUnLine(AnswerActivity.this));
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String resultData = ResultUtils.getResultData(response, AnswerActivity.this);
            }
        });

The above is used when sending form data. The tool class also provides a method for generating json data and a method for not sending data. If you have any questions, you can leave a message at the bottom of the blog.

Guess you like

Origin blog.csdn.net/qq_38821574/article/details/113515546