美文网首页
新手入门 安卓电商系统基于OkHttp3的请求封装

新手入门 安卓电商系统基于OkHttp3的请求封装

作者: Pursue丶 | 来源:发表于2019-12-30 09:59 被阅读0次

    最近有时间闲下来做一些以前工作的复习,翻到了上次的电商项目的代码,想起了那段用别人封装不顺手,自己又不会封装的痛苦时期,所以我决定把自己最终的劳动成果记录下来,方便以后的自己来看一看现在的自己有多蠢2333.

    上次是我第一次做前后端的交互,我对交互的印象只有get ,post,put,delete四种请求,但是并不知道应该怎样具体实现它们,在登录注册以及表单提交中大多使用的是post请求,所以我新建了一个接口类管理这几种数据的提交方式

    
    public interface IHttpClient {
    
        IResponse get(IRequest request);
    
        /**
    
        * json类型的post
    
    *
    
        * @param request
    
        * @return
    
        */
    
        IResponse post(IRequest request);
    
        /**
    
        * 表单类型的post
    
    *
    
        * @param request
    
        * @return
    
        */
    
        IResponse put(IRequest request);
    
        IResponse delete(IRequest request);
    
        IResponse upload_image_post(IRequest request, Map<String, Object> map, File file);
    
    }
    
    

    另外新建IRequest类指定请求的方式,请求头等等

    public interface IRequest {
    
        public static final String POST = "POST";
        public static final String GET = "GET";
        public static final String PUT = "PUT";
        public static final String DELETE = "DELETE";
    
        /**
         * 请求方式
         *
         * @param method
         */
        void setMethod(String method);
    
        /**
         * 指定请求头
         *
         * @param key
         * @param value
         */
        void setHeader(String key, String value);
    
        /**
         * 指定请求信息
         *
         * @param key
         * @param value
         */
        void setBody(String key, Object value);
    
        /**
         * 提供给执行库请求行URL
         *
         * @return
         */
        String getUrl();
    
        /**
         * 提供给执行库请求行URL
         *
         * @return
         */
        Map<String, String> getHeader();
    
        /**
         * 请求体
         *
         * @return
         */
        String getBody();
    }
    

    使用Gson组装请求参数

    public class RequestImpl implements IRequest {
    
        private String method = "POST";
        private String url;
        private Map<String, String> header;
        private Map<String, Object> body;
    
        public RequestImpl(String url) {
            /**
             * 初始化公共参数和头部信息
             */
            this.url = url;
            header = new HashMap();
            body = new HashMap<>();
        }
    
        @Override
        public void setMethod(String method) {
            this.method = method;
        }
    
        @Override
        public void setHeader(String key, String value) {
            header.put(key, value);
        }
    
        @Override
        public void setBody(String key, Object value) {
            body.put(key, value);
        }
    
        @Override
        public String getUrl() {
            if (GET.equals(method)) {
                // 组装post请求参数
                for (String key : body.keySet()) {
                    url = url.replace("${" + key + "}", body.get(key).toString());
                }
            }
            return url;
        }
    
        @Override
        public Map<String, String> getHeader() {
            return header;
        }
    
        @Override
        public String getBody() {
            // 组装post请求参数
            if (body != null) {
                return new Gson().toJson(this.body, HashMap.class);
            } else {
                return "{}";
            }
        }
    }
    

    最后新建请求方法实现类,将四种请求全部重写,然后添加公共执行方法Execute

    public class OkHttpClientImpl implements IHttpClient {
    
        OkHttpClient mOkHttpClient = new OkHttpClient.Builder().build();
    
        @Override
        public IResponse get(IRequest request) {
            /**
             * 解析业务参数
             */
            request.setMethod(IRequest.GET);
            Map<String, String> header = request.getHeader();
            Request.Builder builder = new Request.Builder();
            for (String key : header.keySet()) {
                builder.header(key, header.get(key));
            }
            builder.url(request.getUrl()).get();
            Request okRequest = builder.build();
            return execute(okRequest);
    
        }
    
        /**
         * POST请求
         *
         * @param request
         * @return
         */
        @Override
        public IResponse post(IRequest request) {
            request.setMethod(IRequest.POST);
            MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
            RequestBody requestBody = RequestBody.create(mediaType, request.getBody().toString());
    
            Map<String, String> header = request.getHeader();
            Request.Builder builder = new Request.Builder();
            for (String key : header.keySet()) {
                builder.header(key, header.get(key));
            }
            builder.url(request.getUrl())
                    .post(requestBody);
            Request okRequest = builder.build();
            return execute(okRequest);
        }
    
        /**
         * PUT请求
         *
         * @param request
         * @return
         */
        @Override
        public IResponse put(IRequest request) {
            request.setMethod(IRequest.PUT);
            MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
            RequestBody requestBody = RequestBody.create(mediaType, request.getBody().toString());
    
            Map<String, String> header = request.getHeader();
            Request.Builder builder = new Request.Builder();
            for (String key : header.keySet()) {
                builder.header(key, header.get(key));
            }
            builder.url(request.getUrl())
                    .put(requestBody);
            Request okRequest = builder.build();
            return execute(okRequest);
    
        }
    
        /**
         * GET请求
         *
         * @param request
         * @return
         */
        @Override
        public IResponse delete(IRequest request) {
            request.setMethod(IRequest.DELETE);
            Map<String, String> header = request.getHeader();
            Request.Builder builder = new Request.Builder();
            for (String key : header.keySet()) {
                builder.header(key, header.get(key));
            }
            builder.url(request.getUrl())
                    .delete(null);
            Request okRequest = builder.build();
            return execute(okRequest);
        }
    
        /**
         * 文件上传
         *
         * @param request
         * @param map
         * @param file
         * @return
         */
        @Override
        public IResponse upload_image_post(IRequest request, Map<String, Object> map, File file) {
            /**
             *  实现文件上传
             */
            request.setMethod(IRequest.POST);
            MediaType MEDIA_TYPE_IMAGE = MediaType.parse("image/*");
            MultipartBody.Builder requestBody = new MultipartBody
                    .Builder().setType(MultipartBody.FORM);
            if (file != null) {
                requestBody.addFormDataPart("image", file.getName(),
                        RequestBody.create(MEDIA_TYPE_IMAGE, file));
            }
            if (map != null) {
                // map 里面是请求中所需要的 key 和 value
                for (Map.Entry entry : map.entrySet()) {
                    requestBody.addFormDataPart(valueOf(entry.getKey()), valueOf(entry.getValue()));
                }
            }
            Map<String, String> header = request.getHeader();
            Request.Builder builder = new Request.Builder();
            for (String key : header.keySet()) {
                builder.header(key, header.get(key));
            }
            builder.url(request.getUrl())
                    .post(requestBody.build());
            Request okRequest = builder.build();
            return execute(okRequest);
        }
    
        /**
         * 公共Execute方法
         *
         * @param request
         * @return
         */
        private IResponse execute(Request request) {
            ResponseImpl commonResponse = new ResponseImpl();
    
            try {
                Response response = mOkHttpClient.newCall(request).execute();
                commonResponse.setCode(response.code());
                String body = response.body().string();
                commonResponse.setData(body);
            } catch (IOException e) {
                e.printStackTrace();
                commonResponse.setCode(ResponseImpl.STATE_UNKNOW_ERROR);
                commonResponse.setData(e.getMessage());
            }
            return commonResponse;
        }
    

    到这里封装就基本完成了,没有其他另类的东西,功能都是很基础的请求
    下面有一个简单的使用示例

        使用示例
        IRequest request = new RequestImpl(这里传入url);
        //设置请求头,这里要几个就setHeader几次
        request.setHeader(key,value);
        // 设置请求体 同上
        request.setBody(key,value);
        // 获取一个okhttpclient实例
        IHttpClient mHttpClient = new OkHttpClientImpl();
        // 得到服务器端返回的结果
        IResponse response = mHttpClient.get(request);
    

    注:图片的功能好像不能正常实现,也可能是我app出现问题,下次使用时会着重注意

    相关文章

      网友评论

          本文标题:新手入门 安卓电商系统基于OkHttp3的请求封装

          本文链接:https://www.haomeiwen.com/subject/tlupoctx.html