ios技术交流Android技术交流

Android架构篇-3 网络接口封装

2021-03-04  本文已影响0人  浪人残风

Android架构篇-3 网络接口封装

实现功能:

1.暴露参数请求地址url、请求方法method、请求参数params、请求头header、请求响应response、https请求证书

2.支持get、post、文件上传下载、https证书

以封装OKhttp为例:

接口定义

业务层接口定义

public class BusinessService {
    public static void login(String account, String password, boolean toastError, ServiceHandle<Resp<User>> callBack) {
        Map<String, Object> params = new HashMap<>();
        params.put("account", account);
        params.put("password", password);
        Service.request(InterfaceSuffix.LOGIN, params, HttpMethod.POST, toastError, callBack);
    }
}

module_app_common层接口定义

接口实现功能:

1)API环境切换,如本地静态配置文件数据、swagger mock数据、开发环境数据、测试环境数据、灰度环境数据、生产环境数据

2)上层屏蔽网络出错、后台系统出错、后台业务错误等数据,上层业务只关注正确的接口数据

3)接口返回数据统一模型,不同业务通过范型统一返回

4)debug模式打印接口数据,方便调试和数据监听

5)所有接口统一加上固定请求头,登录后再加上token

package com.wrs.project.module.app.common.service;

import com.google.gson.Gson;
import com.wrs.project.module.app.common.service.entity.Resp;
import com.wrs.project.module.app.common.utils.ToastUtil;
import com.wrs.project.module.common.network.HttpMethod;
import com.wrs.project.module.common.network.NetWorkDownloadCallBack;
import com.wrs.project.module.common.network.NetWorkService;
import com.wrs.project.module.common.network.NetWorkServiceCallBack;
import com.wrs.project.module.common.network.entity.RequestTask;
import com.wrs.project.module.common.utils.activitymgr.ActivityMgr;
import com.wrs.project.module.common.utils.utils.L;


import java.io.InputStream;
import java.util.Map;

public class Service {
    public static String SERVER_HOST = "http://192.168.0.1:8081";
    public static String ERROR_MSG = "网络出错,请稍后再试...";
    public static Gson gson = new Gson();
    public static final String SERVICETAG = "接口日志";

    /**
     *
     * @param suffix url后缀
     * @param params 参数
     * @param httpMethod 请求方法
     * @param toastError 请求出错时是否toast提示用户
     * @param callBack 回调
     * @param <T> 返回的业务模型
     */
    public static <T> void request(String suffix, Map<String, Object> params, HttpMethod httpMethod, boolean toastError, ServiceHandle<T> callBack) {
        Map<String, String> headers = getCommonHeaders();
        String url = SERVER_HOST + suffix;
        http(url, params, headers, httpMethod, new ServiceHandle<T>() {

            @Override
            public void onFail(Exception e) {
                ActivityMgr.getInstance().getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (toastError) {
                            ToastUtil.showToast(ERROR_MSG);
                        }
                        if (null != callBack) {
                            callBack.onFail(e);
                        }
                    }
                });

            }

            @Override
            public void onSuc(T model) {
                ActivityMgr.getInstance().getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (toastError && model instanceof Resp) {
                            Resp resp = (Resp) model;
                            if (!resp.isSuc()) {
                                String msg = resp.getMsg();
                                if (null != msg && msg.length() > 0) {
                                    ToastUtil.showToast(msg);
                                }
                            }
                        }
                        if (null != callBack) {
                            callBack.onSuc(model);
                        }
                    }
                });
            }

            @Override
            public T converJson(String json) throws Exception {
                if (null != callBack) {
                    return callBack.converJson(json);
                } else {
                    return super.converJson(json);
                }
            }
        });

    }

    private static <T> void http(String url, Map<String, Object> params, Map<String, String> headers, HttpMethod httpMethod, ServiceHandle<T> callBack) {
        NetWorkServiceCallBack serviceCallBack = new NetWorkServiceCallBack() {
            @Override
            public void onFailure(Exception e) {
                L.e(SERVICETAG, "url:" + url);
                L.e(SERVICETAG, "Exception" + e.toString());
                if (null != callBack) {
                    callBack.onFail(e);
                }
            }

            @Override
            public void onResponse(String response) {
                L.e(SERVICETAG, "url:" + url);
                L.e(SERVICETAG, "response:" + response);
                if (null != callBack) {
                    try {
                        T model = callBack.converJson(response);
                        callBack.onSuc(model);
                    } catch (Exception e) {
                        callBack.onFail(e);
                    }
                }
            }
        };
        switch (httpMethod) {
            case GET:
            {
                Map requestParams = null;
                if (null != params && !params.isEmpty()) {
                    requestParams = params;
                }
                NetWorkService.request(url, requestParams, headers, httpMethod, serviceCallBack, new  InputStream[]{});
            }
                break;
            case POST:
            {
                String body = "{}";
                if (null != params) {
                    body = gson.toJson(params);
                }
                NetWorkService.postBody(url, body, headers, serviceCallBack, new  InputStream[]{});
            }
                break;
        }

    }

    public static RequestTask downloadFile(String url, String saveDir, final String fileName, Map<String, String> params, Map<String, String> headers, NetWorkDownloadCallBack callBack, InputStream... certificates) {
        return NetWorkService.downloadFile(url, saveDir, fileName, params, headers, callBack, certificates);
    }

    public static Map<String, String> getCommonHeaders(){
        return null;
    }

}

module_common_network层接口定义

  package com.wrs.project.module.common.network;



import com.wrs.project.module.common.network.entity.RequestTask;
import com.wrs.project.module.common.network.okhttp.OkHttpService;

import java.io.File;
import java.io.InputStream;
import java.util.Map;

import okhttp3.Call;

public class NetWorkService {
    public static int CONNECT_TIMEOUT = 10;
    public static int READ_TIMEOUT = 20;
    public static int WRITE_TIMEOUT = 20;

    public static void request(String url, Map<String, String> params, Map<String, String> headers, HttpMethod httpMethod, NetWorkServiceCallBack callBack, InputStream... certificates) {
        OkHttpService.request(url, params, headers, httpMethod, callBack, certificates);
    }

    public static void postBody(String url, String body, Map<String, String> headers, NetWorkServiceCallBack callBack, InputStream... certificates) {
        OkHttpService.postBody(url, body, headers, callBack, certificates);
    }

    public static void postFile(String url, Map<String, String> params, Map<String, String> headers, File file, String fileName, String fileKey, NetWorkServiceCallBack callBack, InputStream... certificates) {
        OkHttpService.postFile(url, params, headers, file, fileName, fileKey, callBack, certificates);
    }

    public static RequestTask downloadFile(String url, String saveDir, final String fileName, Map<String, String> params, Map<String, String> headers, NetWorkDownloadCallBack callBack, InputStream... certificates) {
        Call call = OkHttpService.downloadFile(url, saveDir, fileName, params, headers, callBack, certificates);
        return new RequestTask(call);
    }

}

封装okhttp

package com.wrs.project.module.common.network.okhttp;

import android.text.TextUtils;


import com.wrs.project.module.common.network.HttpMethod;
import com.wrs.project.module.common.network.NetWorkDownloadCallBack;
import com.wrs.project.module.common.network.NetWorkService;
import com.wrs.project.module.common.network.NetWorkServiceCallBack;
import com.wrs.project.module.common.network.SSLUtil;
import com.wrs.project.module.common.network.TrustAllCerts;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpService {
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private static OkHttpService okHttpService;//单例模式

    public static void request(String url, Map<String, String> params, Map<String, String> headers, HttpMethod httpMethod, NetWorkServiceCallBack callBack, InputStream... certificates) {
        switch (httpMethod) {
            case GET:
                get(url, params, headers, callBack, certificates);
                break;
            case POST:
                post(url, params, headers, callBack, certificates);
                break;
            default:
                break;
        }
    }

    public static Call downloadFile(String url, String saveDir, final String fileName, Map<String, String> params, Map<String, String> headers, NetWorkDownloadCallBack downloadCallBack, InputStream... certificates) {
        Request.Builder requestBuilder = new Request.Builder();
        HttpUrl.Builder urlBuilder = HttpUrl.parse(url)
                .newBuilder();
        if (null != params && params.keySet().size() > 0) {
            for (String key : params.keySet()) {
                String value = params.get(key);
                urlBuilder.addQueryParameter(key, value);
            }
        }
        requestBuilder.url(urlBuilder.build());
        addHeaders(requestBuilder, headers);
        Request request = requestBuilder.build();

        OkHttpClient.Builder builder = null;
        if (request.isHttps() && null != certificates && certificates.length > 0) {
            builder = getClientBuilder(certificates);
        } else {
            builder = getIgnoreHttpsClientBuilder(request.isHttps());
        }
        OkHttpClient client = builder.build();
    Call call =  client.newCall(request);
    call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
               if (null != downloadCallBack) {
                   downloadCallBack.onFailure(e);
               }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (null != downloadCallBack) {
                    InputStream is = null;
                    byte[] buf = new byte[2048];
                    int len = 0;
                    FileOutputStream fos = null;
                    String name = getHeaderFileName(response);
                    if (null == name) {
                        name = fileName;
                    }
                    File file = new File(saveDir, name);
                    boolean suc = true;
                    // 储存下载文件的目录
                    try {
                        is = response.body().byteStream();
                        long total = response.body().contentLength();
                       File parent = file.getParentFile();
                       if (!parent.exists()) {
                           parent.mkdirs();
                       }
                        fos = new FileOutputStream(file);
                        long sum = 0;
                        while ((len = is.read(buf)) != -1) {
                            fos.write(buf, 0, len);
                            sum += len;
                            float progress = sum * 1.0f / total ;
                            if (null != downloadCallBack) {
                                downloadCallBack.onProgress(progress);
                            }
                        }
                        fos.flush();

                    } catch (Exception e) {
                        suc = false;
                        if (null != downloadCallBack) {
                            downloadCallBack.onFailure(e);
                        }
                    } finally {
                        try {
                            if (is != null) {
                                is.close();
                            }
                        } catch (IOException e) {
                        }
                        try {
                            if (fos != null) {
                                fos.close();
                            }
                        } catch (IOException e) {
                        }
                        if (suc && null != downloadCallBack) {
                            downloadCallBack.onSuccess(file);
                        }
                    }

                }
            }
        });
        return call;
    }

    private static String getHeaderFileName(Response response) {
        String dispositionHeader = response.header("Content-Disposition");
        if (!TextUtils.isEmpty(dispositionHeader)) {
            dispositionHeader.replace("attachment;filename=", "");
            dispositionHeader.replace("filename*=utf-8", "");
            String[] strings = dispositionHeader.split("; ");
            if (strings.length > 1) {
                dispositionHeader = strings[1].replace("filename=", "");
                dispositionHeader = dispositionHeader.replace("\"", "");
                return dispositionHeader;
            }
            return null;
        }
        return null;
    }


//    private String isExistDir(String saveDir) throws IOException {
//        // 下载位置
//        File downloadFile = new File(context.getExternalFilesDir(null), saveDir);
//        if (!downloadFile.mkdirs()) {
//            downloadFile.createNewFile();
//        }
//        String savePath = downloadFile.getAbsolutePath();
//        return savePath;
//    }

    public static OkHttpService getInstance() {
        if (okHttpService == null) {
            synchronized (OkHttpService.class) {
                if (okHttpService == null) {
                    okHttpService = new OkHttpService();
                }
            }
        }
        return okHttpService;
    }

    public static void get(String url, Map<String, String> params, Map<String, String> headers, NetWorkServiceCallBack callBack, InputStream... certificates) {
        Request.Builder requestBuilder = new Request.Builder();
        HttpUrl.Builder urlBuilder = HttpUrl.parse(url)
                .newBuilder();
        if (null != params && params.keySet().size() > 0) {
            for (String key : params.keySet()) {
                String value = params.get(key);
                urlBuilder.addQueryParameter(key, value);
            }
        }
        requestBuilder.url(urlBuilder.build());
        addHeaders(requestBuilder, headers);
        Request request = requestBuilder.build();
        startRequest(request, callBack, certificates);
    }

    public static void post(String url, Map<String, String> params, Map<String, String> headers, NetWorkServiceCallBack callBack, InputStream... certificates) {
        FormBody.Builder bodyBuilder = new FormBody.Builder();
        addParams(bodyBuilder, params);
        RequestBody body = bodyBuilder.build();
        Request.Builder requestBuild = new Request.Builder();
        requestBuild.url(url);
        requestBuild.post(body);
        addHeaders(requestBuild, headers);
        Request request = requestBuild.build();
        startRequest(request, callBack, certificates);
    }

    public static void postBody(String url, String body, Map<String, String> headers, NetWorkServiceCallBack callBack, InputStream... certificates) {
        RequestBody requestBody = RequestBody.create(JSON, body);
        Request.Builder requestBuild = new Request.Builder();
        requestBuild.url(url);
        requestBuild.post(requestBody);
        addHeaders(requestBuild, headers);
        Request request = requestBuild.build();
        startRequest(request, callBack, certificates);
    }

    public static void postFile(String url, Map<String, String> params, Map<String, String> headers, File file, String fileName, String fileKey, NetWorkServiceCallBack callBack, InputStream... certificates) {
        RequestBody requestBody =  RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
        builder.addFormDataPart(fileKey, fileName, requestBody);
        if (null != params && params.keySet().size() > 0) {
            for (String key : params.keySet()) {
                String value = params.get(key);
                if (null != value) {
                    builder.addFormDataPart(key, value);
                }
            }
        }

        Request.Builder requestBuild = new Request.Builder();
        requestBuild.url(url);
        requestBuild.post(builder.build());
        addHeaders(requestBuild, headers);
        Request request = requestBuild.build();
        startRequest(request, callBack, certificates);
    }

    public static void addParams(FormBody.Builder builder, Map<String, String> params) {
        if (null != params && params.keySet().size() > 0) {
            for (String key : params.keySet()) {
                String value = params.get(key);
                if (null != value) {
                    builder.add(key, value);
                }
            }
        }
    }

    public static void addHeaders(Request.Builder builder, Map<String, String> headers) {
        if (null != headers && headers.keySet().size() > 0) {
            for (String key : headers.keySet()) {
                String value = headers.get(key);
                if (null != value) {
                    builder.header(key, value);
                }
            }
        }
    }

    public static void startRequest(Request request, NetWorkServiceCallBack callBack, InputStream... certificates) {
        OkHttpClient.Builder builder = null;
        if (request.isHttps() && null != certificates && certificates.length > 0) {
            builder = getClientBuilder(certificates);
        } else {
            builder = getIgnoreHttpsClientBuilder(request.isHttps());
        }

        builder.connectTimeout(NetWorkService.CONNECT_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(NetWorkService.READ_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(NetWorkService.WRITE_TIMEOUT, TimeUnit.SECONDS);
        OkHttpClient client = builder.build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (null != callBack) {
                    callBack.onFailure(e);
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (null != callBack) {
                    callBack.onResponse(response.body().string());
                }
            }
        });
    }

    public static OkHttpClient.Builder getIgnoreHttpsClientBuilder(Boolean isHttps) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        if (isHttps) {
            HostnameVerifier hostnameVerifier = new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            };
            X509TrustManager xtm = new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType) {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType) {
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    X509Certificate[] x509Certificates = new X509Certificate[0];
                    return x509Certificates;
                }
            };

            SSLContext sslContext = null;
            try {
                sslContext = SSLContext.getInstance("SSL");
                sslContext.init(null, new TrustManager[]{xtm}, new SecureRandom());
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (KeyManagementException e) {
                e.printStackTrace();
            }
            builder.sslSocketFactory(sslContext.getSocketFactory(), xtm);
            builder.hostnameVerifier(hostnameVerifier);
        }
        return builder;
    }


    public static OkHttpClient.Builder getClientBuilder(InputStream... certificates) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        SSLSocketFactory sslSocketFactory = SSLUtil.getSSLSocketFactory(certificates);
        X509TrustManager xtm = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                X509Certificate[] x509Certificates = new X509Certificate[0];
                return x509Certificates;
            }
        };
//        builder.sslSocketFactory(SSLUtil.getSSLSocketFactory(fiddleCerInStream, inStream));
        builder.sslSocketFactory(sslSocketFactory, xtm);
        builder.hostnameVerifier(new TrustAllCerts.TrustAllHostnameVerifier());
        return builder;
    }


}

源码下载

上一篇下一篇

猜你喜欢

热点阅读