修罗

OkHttp封装(Java)
OkHttp封装(Java)OkHttp官网添加依赖implementation group: 'com.squa...
扫描右侧二维码阅读全文
16
2023/03

OkHttp封装(Java)

OkHttp封装(Java)

OkHttp官网

添加依赖

implementation group: 'com.squareup.okhttp3', name: 'okhttp', version: '4.10.0'

创建两个java类

  • XiuRequest请求类
  • ResponseCallback请求回调接口

image-20230316134118104.png

定义请求类

import android.content.Context;
import android.content.Intent;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import java.util.Map.Entry;

public class XiuRequest {
    // okhttp实例
    private static final OkHttpClient client = new OkHttpClient();
    // 请求类实例
    private static XiuRequest xiuRequest;
    // 上下文,用来请求业务,如token过期跳转至登录页
    private Context context;
    // 私有的构造方法
    private XiuRequest(){}
    

    // get方法只传url和请求回调函数
    public void get(String url, ResponseCallback responseCallback) {
        Request builder = new Request.Builder().url(url).build();
        // resDataHandle回调在本类统一处理
        client.newCall(builder).enqueue(resDataHandle(responseCallback));
    }
    
    
    // get方法传url、map参数集合、请求回调函数
    public void get(String url,Map<String, Object> map, ResponseCallback responseCallback) {
        String appendUrl = getAppendUrl(url, map);
        //Log.d("url", "get: "+appendUrl);
        Request builder = new Request.Builder().url(appendUrl).build();
        client.newCall(builder).enqueue(resDataHandle(responseCallback));
    }

    
    // post方法传url、map参数集合、请求回调函数
    // 请求参数是json格式数据
    public void post(String url, HashMap<String, Object> map, ResponseCallback responseCallback){
        // 组建数据
        JSONObject jsonObj = new JSONObject(map);
        RequestBody requestBody = RequestBody.create(String.valueOf(jsonObj), MediaType.parse("application/json;charset=utf-8"));
        // 创建request
        okhttp3.Request request = new okhttp3.Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        // 发起请求
        client.newCall(request).enqueue(resDataHandle(responseCallback));
    }
    

    // 请求类实例获取静态方法
    public static XiuRequest getRequestInstance(Context context){
        if(xiuRequest == null){
            xiuRequest = new XiuRequest();
        }
        xiuRequest.context = context.getApplicationContext();
        return xiuRequest;
    }
    

    // 回调统一处理
    private Callback resDataHandle(ResponseCallback responseCallback){
        return new Callback() {
            // 统一请求错误处理
            @Override
            public void onFailure(Call call, IOException e) {
                // 交给每次请求传递的回调
                responseCallback.onFailure(e);
            }

            // 统一响应数据处理
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                assert response.body() != null;
                // 连续两次调用response.body().string(),就会抛出异常,数据流已经关闭
                String responseString = response.body().string();
                try {
                    JSONObject jsonObject = new JSONObject(responseString);
                    //// 业务处理
                    String code = jsonObject.getString("code");
                    if(code.equals("401")){
                        Intent intent = new Intent(context, LoginActivity.class);
                        context.startActivity(intent);
                    }
                    ////
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                // 交给每次请求传递的回调
                responseCallback.onResponse(responseString);

            }
        };
    }
    

    // 将map集合转为query参数追加到url地址后面
    // url + ?name=xiuLuo
    private String getAppendUrl(String url, Map<String, Object> map) {
        if (map != null && !map.isEmpty()) {
            StringBuffer buffer = new StringBuffer();
            Iterator<Entry<String, Object>> iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Entry<String, Object> entry = iterator.next();
                if (buffer.toString().length() == 0) {
                    buffer.append("?");
                } else {
                    buffer.append("&");
                }
                buffer.append(entry.getKey()).append("=").append(entry.getValue());
            }
            url += buffer.toString();
        }
        return url;
    }
}

请求回调接口

public interface ResponseCallback{
    abstract void onResponse(String res);
    abstract void onFailure(IOException e);
}

请求类使用

HashMap<String, Object> m = new HashMap<>();
m.put("mobile", username);
m.put("password", password);

// 发送登录请求
XiuRequest.getRequestInstance(this).post("/login", m, new ResponseCallback() {
    @Override
    public void onFailure(IOException e) {
        Log.d("请求出错:", e.getMessage());
    }

    @Override
    public void onResponse(String response) {
        Log.d("res:", response);
        // 将response这个json字符串转java对象(一般用gson),再进行业务操作
        // ...
        
    }
});

image-20230316115909121.png

Last modification:March 16th, 2023 at 01:46 pm

Leave a Comment