当前位置: 首页 > 工具软件 > OkHttpFinal > 使用案例 >

Android使用okhttpfinal+gson实现网络请求

郎永福
2023-12-01

Android使用okhttpfinal+gson实现网络请求

近期整理了[okhttpfinal][6]+[gson][6] 实现网络请求和解析功能,特做此笔记:

代码部分

首先需要在build.gradle中导入包okhttpfinal,gson:

compile 'com.google.code.gson:gson:2.2.4'
compile 'com.jakewharton:butterknife:7.0.0'

在使用okhttpfinal之前需要初始化,建议放到Application中

         /**
         * 初始化OkHttpFinal
         */
        OkHttpFinalConfiguration.Builder builder = new OkHttpFinalConfiguration.Builder();
        //设置请求超时时间
        builder.setTimeout(60000);
        //初始化OkHttpFinalConfiguration
        OkHttpFinal.getInstance().init(builder.build());

创建IRequestCallback接口用来返回请求状态

public interface IRequestCallback<T> {
    /**
     * 执行网络访问之前的操作
     */
    void onStart(String msg);

    /**
     * 返回结果错误或解析失败
     */
    void onFailed(String msg);

    /**
     * 返回结果成功或解析成功
     */
    void onSuccessed(T t);
}

构建RequestParamsBuilder请求头类,用来封装公共请求头

public class RequestParamsBuilder {

    public static RequestParams buildRequestParams(HttpCycleContext context) {
        String token = "";
        RequestParams params = new RequestParams(context);
        /**
         * 公共请求头
         */
        params.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
        /**
         * 登录状态的token
         */
//        params.addFormDataPart("token","token");
        return params;
    }

    /**
     * 服务端返回错误信息,解析得到message
     * 如果返回数据解析异常时可调用该方法
     */
    public static String getMessage(String errorJson) {
        try {
            Gson gson = new Gson();
            NetErrorBean errorBean = gson.fromJson(errorJson, NetErrorBean.class);
            String errorMsg = errorBean.getMessage();
            errorMsg = errorMsg == null ? "" : errorJson;
            return errorMsg;
        } catch (Exception e) {
            return e.getMessage();
        }
    }
}

至于NetErrorBean类里面只包括了
/**
* key :
* message :
*/

创建RequestServer类

public class RequestServer {
    private HttpCycleContext context;

    public RequestServer(HttpCycleContext context) {
        this.context = context;
    }

    //传字符串参数
    public void getRequestServer(String request, IRequestCallback<DataResponse> callback) {
        RequestParams requestParams = RequestParamsBuilder.buildRequestParams(context);
        requestParams.addFormDataPart("request", request);
        getRequestServer(requestParams,callback);
    }
    //直接请求对象的参数
    public void getRequestServer(RequestParams params, final IRequestCallback<DataResponse> call) {
        final String msg = "";
        HttpRequest.get("http://wthrcdn.etouch.cn/weather_mini?", params, new BaseHttpRequestCallback() {
            @Override
            public void onStart() {
                super.onStart();
                if (call != null) {
                    call.onStart(msg);
                }
            }

            @Override
            public void onResponse(String response, Headers headers) {
                super.onResponse(response, headers);
                if (response != null) {
                    try {
                        Gson gson = new Gson();
                        DataResponse dataResponse = gson.fromJson(response, DataResponse.class);
                        /**
                         * 如果返回的是该类型的list数据,使用如下方法
                         */
//                        List<DataResponse> dataResponses = gson.fromJson(response,new TypeToken<List<DataResponse>>(){}.getType());
                        if (dataResponse != null) {
                            if (dataResponse.getDesc() != null) {
                                int code = dataResponse.getStatus();
                                if (code==1000) {
                                    call.onSuccessed(dataResponse);
                                } else {
                                    call.onFailed(dataResponse.getDesc());
                                }
                            }
                        }
                    } catch (JsonSyntaxException e) {
                        e.printStackTrace();
                        //异常中可以处理解析失败的json串
                        //call.onFailed(RequestParamsBuilder.getMessage(response));
                        call.onFailed(e.getMessage());
                    }
                }
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                super.onFailure(errorCode, msg);
                if (call!=null){
                    call.onFailed(msg);
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                /**
                 * 请求结束,不管成功与否都会执行,可在此处写dialog消失逻辑等等
                 */
            }
        });

    }
}

哦,还需要一个解析返回json串的对象,创建DataResponse类
这是天气预报请求的数据,该类里面有两个重写的方法(clone,equals)可以注意下,虽然这里没什么卵用

public class DataResponse implements Serializable,Cloneable{

    /**
     * data : {"yesterday":{"date":"21日星期日","high":"高温 31℃","fx":"南风","low":"低温 18℃","fl":"3-4级","type":"多云"},"city":"北京","aqi":"33","forecast":[{"date":"22日星期一","high":"高温 18℃","fengli":"3-4级","low":"低温 13℃","fengxiang":"东北风","type":"小到中雨"},{"date":"23日星期二","high":"高温 28℃","fengli":"微风级","low":"低温 14℃","fengxiang":"南风","type":"晴"},{"date":"24日星期三","high":"高温 32℃","fengli":"3-4级","low":"低温 17℃","fengxiang":"西南风","type":"多云"},{"date":"25日星期四","high":"高温 33℃","fengli":"3-4级","low":"低温 16℃","fengxiang":"南风","type":"晴"},{"date":"26日星期五","high":"高温 32℃","fengli":"微风级","low":"低温 18℃","fengxiang":"南风","type":"晴"}],"ganmao":"相对于今天将会出现大幅度降温,易发生感冒,注意增加衣服,加强自我防护避免感冒。","wendu":"16"}
     * status : 1000
     * desc : OK
     */

    private DataBean data;
    private int status;
    private String desc;

    public DataBean getData() {
        return data;
    }

    public void setData(DataBean data) {
        this.data = data;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public static class DataBean {
        /**
         * yesterday : {"date":"21日星期日","high":"高温 31℃","fx":"南风","low":"低温 18℃","fl":"3-4级","type":"多云"}
         * city : 北京
         * aqi : 33
         * forecast : [{"date":"22日星期一","high":"高温 18℃","fengli":"3-4级","low":"低温 13℃","fengxiang":"东北风","type":"小到中雨"},{"date":"23日星期二","high":"高温 28℃","fengli":"微风级","low":"低温 14℃","fengxiang":"南风","type":"晴"},{"date":"24日星期三","high":"高温 32℃","fengli":"3-4级","low":"低温 17℃","fengxiang":"西南风","type":"多云"},{"date":"25日星期四","high":"高温 33℃","fengli":"3-4级","low":"低温 16℃","fengxiang":"南风","type":"晴"},{"date":"26日星期五","high":"高温 32℃","fengli":"微风级","low":"低温 18℃","fengxiang":"南风","type":"晴"}]
         * ganmao : 相对于今天将会出现大幅度降温,易发生感冒,注意增加衣服,加强自我防护避免感冒。
         * wendu : 16
         */

        private YesterdayBean yesterday;
        private String city;
        private String aqi;
        private String ganmao;
        private String wendu;
        private List<ForecastBean> forecast;

        public YesterdayBean getYesterday() {
            return yesterday;
        }

        public void setYesterday(YesterdayBean yesterday) {
            this.yesterday = yesterday;
        }

        public String getCity() {
            return city;
        }

        public void setCity(String city) {
            this.city = city;
        }

        public String getAqi() {
            return aqi;
        }

        public void setAqi(String aqi) {
            this.aqi = aqi;
        }

        public String getGanmao() {
            return ganmao;
        }

        public void setGanmao(String ganmao) {
            this.ganmao = ganmao;
        }

        public String getWendu() {
            return wendu;
        }

        public void setWendu(String wendu) {
            this.wendu = wendu;
        }

        public List<ForecastBean> getForecast() {
            return forecast;
        }

        public void setForecast(List<ForecastBean> forecast) {
            this.forecast = forecast;
        }

        public static class YesterdayBean {
            /**
             * date : 21日星期日
             * high : 高温 31℃
             * fx : 南风
             * low : 低温 18℃
             * fl : 3-4级
             * type : 多云
             */

            private String date;
            private String high;
            private String fx;
            private String low;
            private String fl;
            private String type;

            public String getDate() {
                return date;
            }

            public void setDate(String date) {
                this.date = date;
            }

            public String getHigh() {
                return high;
            }

            public void setHigh(String high) {
                this.high = high;
            }

            public String getFx() {
                return fx;
            }

            public void setFx(String fx) {
                this.fx = fx;
            }

            public String getLow() {
                return low;
            }

            public void setLow(String low) {
                this.low = low;
            }

            public String getFl() {
                return fl;
            }

            public void setFl(String fl) {
                this.fl = fl;
            }

            public String getType() {
                return type;
            }

            public void setType(String type) {
                this.type = type;
            }
        }

        public static class ForecastBean {
            /**
             * date : 22日星期一
             * high : 高温 18℃
             * fengli : 3-4级
             * low : 低温 13℃
             * fengxiang : 东北风
             * type : 小到中雨
             */

            private String date;
            private String high;
            private String fengli;
            private String low;
            private String fengxiang;
            private String type;

            public String getDate() {
                return date;
            }

            public void setDate(String date) {
                this.date = date;
            }

            public String getHigh() {
                return high;
            }

            public void setHigh(String high) {
                this.high = high;
            }

            public String getFengli() {
                return fengli;
            }

            public void setFengli(String fengli) {
                this.fengli = fengli;
            }

            public String getLow() {
                return low;
            }

            public void setLow(String low) {
                this.low = low;
            }

            public String getFengxiang() {
                return fengxiang;
            }

            public void setFengxiang(String fengxiang) {
                this.fengxiang = fengxiang;
            }

            public String getType() {
                return type;
            }

            public void setType(String type) {
                this.type = type;
            }
        }
    }

    /**
     * 对象克隆,代码中使用dataResponse.clone()方法快速克隆对象,
     * @return
     * @throws CloneNotSupportedException
     */
    @Override
    protected Object clone() throws CloneNotSupportedException {
        DataResponse dataResponse=(DataResponse) super.clone();
        return dataResponse;
    }

    /**
     * 使用城市(唯一性的标识)判断两个数据对象是否一致
     *  使用该类集合调用contains方法判断是否存在该对象
     * @param o
     * @return
     */
    @Override
    public boolean equals(Object o) {
        if(o instanceof DataResponse){
            DataResponse dataResponse=(DataResponse) o;
            //三元运算符:如果city是null直接返回false,如果不是返回是否相同
            return this.getData().city==null?false:this.getData().city.equals(dataResponse.getData().city);
        }
        return false;
    }

    @Override
    public int hashCode() {
        int result = data != null ? data.hashCode() : 0;
        result = 31 * result + status;
        result = 31 * result + (desc != null ? desc.hashCode() : 0);
        return result;
    }
}

准备工作结束,下面在主activity中实现HttpCycleContext

//请求之前
private RequestServer requestServer;
requestServer = new RequestServer(this);
//网络请求OKhttp
sendRequest();
//sendRequest方法实现网络请求和返回数据处理
private void sendRequest() {
        RequestParams params = new RequestParams();
//        Gson gson=new Gson();
//        DataRequest dataRequest=new DataRequest();
//        dataRequest.setUsername("name");
//        String Strparams=gson.toJson(dataRequest);
        params.addFormDataPart("city", "北京");
        requestServer.getRequestServer(params, new IRequestCallback<DataResponse>() {
            @Override
            public void onStart(String msg) {
                /**
                 * 开始请求
                 */
            }

            @Override
            public void onFailed(String msg) {
                /**
                 * 返回失败
                 */
            }

            @Override
            public void onSuccessed(DataResponse dataResponse) {
                /**
                 * 成功
                 */
//                Gson gson=new Gson();
                if (dataResponse.getData().getGanmao() != null) {
                    text_wenzi.setText(dataResponse.getData().getGanmao().toString());
                }
            }
        });
    }
 类似资料: