IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 移动开发 -> Android 封装okhttp3网络请求拓展 -> 正文阅读

[移动开发]Android 封装okhttp3网络请求拓展

本篇只展示更新的代码,没有变化的就不贴了。
上一篇 :Android 封装okhttp3网络请求

更新内容:

  • 上传文件
  • 下载文件
  • 表单post请求
  • 增加时间限制

JsonParse

public class JsonParse {

    private Object responseBodyResult;

    public Object getResponseBodyResult() {
        return responseBodyResult;
    }

    /**
     * 请求体转请求json字符串
     *
     * @param requestEntity 请求对象
     * @return params字符串
     */
    public String toGetJson(RequestEntity requestEntity) {
        StringBuilder params = new StringBuilder("?");
        try {
            Class cls = requestEntity.getClass();
            Field[] fields = cls.getDeclaredFields();
            for (Field field : fields) {
                params.append(field.getName());
                params.append("=");
                params.append(field.get(requestEntity));
                params.append("&");
            }

        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return params.substring(0, params.length() - 1);
    }

    public String toPostJson(RequestEntity requestEntity) {
        return new FilterGson().toJson(requestEntity);
    }

    public FormBody toFormBody(RequestEntity requestEntity) {
        FormBody.Builder build = new FormBody.Builder();
        try {
            Class cls = requestEntity.getClass();
            Field[] fields = cls.getDeclaredFields();
            for (Field field : fields) {
                field.get(requestEntity);
                build.add(field.getName(), String.valueOf(field.get(requestEntity)));
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return build.build();
    }

    public RequestBody toRequestBody(String name, String sFile) {
        MediaType mediaType = MediaType.parse("multipart/form-data; charset=utf-8");
        RequestBody requestBody = RequestBody.Companion.create(new File(sFile), mediaType);
        return new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", name, requestBody)
                .build();
    }

    public RequestBody toRequestBody(List<String> names, List<String> sFiles) {
        MediaType mediaType = MediaType.parse("multipart/form-data; charset=utf-8");
        if (names.size() == sFiles.size()) {
            MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
            for (int i = 0; i < sFiles.size(); i++) {
                RequestBody requestBody = RequestBody.Companion.create(new File(sFiles.get(i)), mediaType);
                builder.addFormDataPart("files", names.get(i), requestBody);
            }
            return builder.build();
        }
        return null;
    }

    public void parseJson(String json, Type type) {
        try {
            JSONObject jsonObject = new JSONObject(json);

            String jsonBody = jsonObject.get("data").toString();
            if (NetConstant.NULL.equals(jsonBody) || NetConstant.NULL_SLASH.equals(jsonBody)) {
                try {
                    jsonBody = "{}";
                    responseBodyResult = new FilterGson().fromJson(jsonBody, type);
                } catch (Exception e) {
                    jsonBody = "[]";
                    responseBodyResult = new FilterGson().fromJson(jsonBody, type);
                }
            } else {
                responseBodyResult = new FilterGson().fromJson(jsonBody, type);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

HttpManager

public class HttpManager {

    public static void init(String ip, String post) {
        baseIp = ip;
        basePort = post;
    }

    private static String baseIp;
    private static String basePort;

    private static String getRequestUrl(String action) {
        String baseUrl = "http://%s:%s/offline/%s/";
        return String.format(baseUrl, baseIp, basePort, action);
    }

    public static void getAsyn(String url, OkHttpManager.BaseCallback callback) {
        OkHttpManager.getInstance().getAsyn(url, callback);
    }

    public static void getAsyn(RequestEntity requestEntity, OkHttpManager.BaseCallback callback) {
        OkHttpManager.getInstance().getAsyn(getRequestUrl(requestEntity.getUrlName()) + new JsonParse().toGetJson(requestEntity), callback);
    }

    public static void postAsyn(RequestEntity requestEntity, OkHttpManager.BaseCallback callback) {
        OkHttpManager.getInstance().postAsyn(getRequestUrl(requestEntity.getUrlName()), new JsonParse().toPostJson(requestEntity), callback);
    }

    public static void formBodyAsyn(RequestEntity requestEntity, OkHttpManager.BaseCallback callback) {
        OkHttpManager.getInstance().postAsyn(getRequestUrl(requestEntity.getUrlName()), new JsonParse().toFormBody(requestEntity), callback);
    }

    public static void uploadAsyn(String url, String name, String file, OkHttpManager.BaseCallback callback) {
        OkHttpManager.getInstance().uploadAsyn(url, new JsonParse().toRequestBody(name, file), callback);
    }

    public static void uploadAsyn(String url, List<String> names, List<String> sFiles, OkHttpManager.BaseCallback callback) {
        OkHttpManager.getInstance().uploadAsyn(url, new JsonParse().toRequestBody(names, sFiles), callback);
    }

    public static void downloadAsyn(String url, String filePath, OkHttpManager.BaseCallback callback) {
        OkHttpManager.getInstance().downloadAsyn(url, filePath, callback);
    }
}

OkHttpManager

public class OkHttpManager {

    private final Handler mHandler;
    private final OkHttpClient okHttpClient;

    private OkHttpManager() {
        okHttpClient = new OkHttpClient.Builder()
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .connectTimeout(10, TimeUnit.SECONDS)
                .build();
        mHandler = new Handler(Looper.getMainLooper());
    }

    public static OkHttpManager getInstance() {
        return OkHttpHolder.okHttpManager;
    }

    private static class OkHttpHolder {
        private static OkHttpManager okHttpManager = new OkHttpManager();
    }

    /**
     * get请求
     *
     * @param url      地址
     * @param callback 回调
     */
    public void getAsyn(String url, final BaseCallback callback) {
        final Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        send(request, callback);
    }

    /**
     * post请求
     *
     * @param url         地址
     * @param requestBody String字符串参数
     * @param callback    回调
     */
    public void postAsyn(String url, String requestBody, final BaseCallback callback) {
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.Companion.create(requestBody, mediaType))
                .build();
        send(request, callback);
    }

    /**
     * post请求
     *
     * @param url      地址
     * @param body     键值对请求
     * @param callback 回调
     */
    public void postAsyn(String url, FormBody body, BaseCallback callback) {
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        send(request, callback);
    }

    /**
     * 上传文件
     *
     * @param url      路径
     * @param body     文件
     * @param callback 回调
     */
    public void uploadAsyn(String url, RequestBody body, BaseCallback callback) {
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        send(request, callback);
    }

    /**
     * 下载文件
     *
     * @param url      地址
     * @param callback 回调
     */
    public void downloadAsyn(String url, String filePath, BaseCallback callback) {
        Request request = new Request.Builder().url(url).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                sendFailCallback(callback, call.toString());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) {
                if (response.isSuccessful()) {
                    ResponseBody body = response.body();
                    if (body != null) {
                        writeFile(body,filePath);
                    }
                }
            }
        });
    }

    /**
     * 发送服务器
     *
     * @param request  内容
     * @param callback 回调
     * @param get
     */
    private void send(Request request, final BaseCallback callback) {
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                sendFailCallback(callback, call.toString());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (HttpCode.CODE_200 == response.code()) {
                    JsonParse jsonParse = new JsonParse();
                    jsonParse.parseJson(response.body().string(), callback.mType);
                    sendSuccessCallBack(callback, jsonParse.getResponseBodyResult());
                } else {
                    sendFailCallback(callback, HttpCode.CODE_9999_MSG);
                }
            }
        });
    }

    /**
     * 下载完成后写文件
     *
     * @param body     结果地址
     * @param filePath 保存地址
     */
    private void writeFile(ResponseBody body, String filePath) {
        InputStream is;
        FileOutputStream fos = null;
        is = body.byteStream();
        File file = new File(filePath);
        try {
            fos = new FileOutputStream(file);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * UI线程中执行操作成功回调
     *
     * @param callback     回调类
     * @param responseBody 服务器响应的body
     */
    private void sendSuccessCallBack(final BaseCallback callback, final Object responseBody) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (null != callback) {
                    callback.onSuccess(responseBody);
                }
            }
        });
    }

    /**
     * UI线程中执行操作失败回调
     *
     * @param callback 回调类
     * @param msg      错误信息
     */
    private void sendFailCallback(final BaseCallback callback, final String msg) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (null != callback) {
                    callback.onFailure(msg);
                }
            }
        });
    }

    public static abstract class BaseCallback<T> {

        Type mType;

        public BaseCallback() {
            mType = getSuperclassTypeParameter(getClass());
        }

        static Type getSuperclassTypeParameter(Class<?> subclass) {
            Type superclass = subclass.getGenericSuperclass();
            if (superclass instanceof Class) {
                throw new RuntimeException("Enter generics in BaseResultCallback");
            }
            ParameterizedType parameterized = (ParameterizedType) superclass;
            return parameterized.getActualTypeArguments()[0];
        }

        public abstract void onFailure(String message);

        public abstract void onSuccess(T result);
    }
}
  移动开发 最新文章
Vue3装载axios和element-ui
android adb cmd
【xcode】Xcode常用快捷键与技巧
Android开发中的线程池使用
Java 和 Android 的 Base64
Android 测试文字编码格式
微信小程序支付
安卓权限记录
知乎之自动养号
【Android Jetpack】DataStore
上一篇文章      下一篇文章      查看所有文章
加:2021-09-11 18:56:29  更:2021-09-11 18:58:58 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/23 17:00:38-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码