android 解析报文的相关类封装,LIteHttp的简单使用

来源:互联网 发布:买域名和空间 编辑:程序博客网 时间:2024/06/05 23:54

Json解析通用类

这里的Json是fastJson,当然也可以使用Gson等进行替换

import java.util.List;import java.util.Map;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONArray;import com.alibaba.fastjson.JSONObject;public class JsonUtils {    public static <T> T json2Class(String json, Class<T> clazz) {        return JSON.parseObject(json, clazz);      }    public static <T> List<T> json2List(String json, Class<T> clazz) {        return  JSON.parseArray(json, clazz);    }    public static <T> List<T> jsonArr2List(JSONArray arr, Class<T> clazz) {        return  JSON.parseArray(JSON.toJSONString(arr), clazz);    }    public static <T> String x2json(Object object) {        return  JSON.toJSONString(object);      }    public static JSONObject string2json(String str) {        return  JSON.parseObject(str);    }    @SuppressWarnings("unchecked")    public static Map<String, Object> json2Map(String json) {        return (Map<String, Object>)JSON.parse(json);      }}

Json报文解析的相关报文承接和发送的实体类

请求报文的封装实体

public class BaseRequestEntity<T> {    private T data = null;    public BaseRequestEntity(T data) {        this.data = data;    }    public T getData() {        return data;    }    public void setData(T data) {        this.data = data;    }}

承接报文的封装实体

public class BaseResponseEntity<T> implements Serializable {    /**     * 返回码:0表示执行成功,否则失败     * */    private String code = "";    /**     * 返回消息     * */    private String message = "";    /**     * 执行成功时返回的结果对象     * */    private T data = null;    public String getCode() {        return code;    }    public void setCode(String code) {        this.code = code;    }    public String getMessage() {        return message;    }    public void setMessage(String message) {        this.message = message;    }    public T getData() {        return data;    }    public void setData(T data) {        this.data = data;    }

到此为止呢,Json相关的类基本介绍完毕了,两个实体类的封装只是针对我们项目的要求而定的,我们可以针对项目本身去自定义实体类的解析节点

使用统一实体类的原因就是达到一致性,方便后期对代码的维护,降低成本,下面就是我们项目实际Json

{    'code': 0,    'data': {        'CostTotal': '45003.85',        'PrepaidPayment': '8010.00',        'ExpenseBalance': '-36993.85'    }}

LiteHttp jar包的使用

好了,Json说完了,那我们来说说网络请求的实体类封装吧,其实很简单,Android已经为我们Android开发者提供了封装好了的网络请求类,但这里我们使用的是现成的Jar包—-LiteHttp

使用过网络请求的同学一定会知道请求用到最多的就是 Get Post,好了言归正传,我们直接看下网路请求的类封装吧,当然这个网络请求是个异步请求,如果你需要同步的请求,自己修改吧

/** * 异步请求 */public class AsyncHttpClient {    private LiteHttp httpClient;    private MainApplication appContext;    public AsyncHttpClient(MainApplication appContext) {        this.appContext = appContext;        this.initLiteHttp();    }    private void initLiteHttp() {        if (httpClient == null) {            HttpConfig config = new HttpConfig(appContext) // configuration                                                            // quickly                    .setDebugged(false) // log output when debugged                    .setDetectNetwork(true) // detect network before connect                    .setDoStatistics(true) // statistics of time and traffic                    .setUserAgent("Mozilla/5.0 (...)") // set custom User-Agent                    .setTimeOut(5000, 5000)// connect and socket timeout:                    .setMaxMemCacheBytesSize(1*1000*1000)//1M                    .setSocketBufferSize(1*1000*1000);//1M                    ;             httpClient = LiteHttp.newApacheHttpClient(config);        } else {            httpClient.getConfig() // configuration directly                    .setDebugged(false) // log output when debugged                    .setDetectNetwork(true) // detect network before connect                    .setDoStatistics(true) // statistics of time and traffic                    .setUserAgent("Mozilla/5.0 (...)") // set custom User-Agent                    .setSocketBufferSize(1*1000*1000)//1M                    .setMaxMemCacheBytesSize(1*1000*1000)//1M                    .setTimeOut(5000, 5000); // connect and socket timeout:                                                // 10s        }    }    public void get(String url, final HttpResponseListener responseListener) {        final StringRequest request = new StringRequest(url).setMethod(HttpMethods.Get);        request.setHttpListener(new HttpListener<String>() {            @Override            public void onSuccess(String res, Response<String> response) {                responseListener.onSuccess(response.getHttpStatus().getCode() + "", res);            }            @Override            public void onFailure(HttpException e, Response<String> response) {                responseListener.onFailure(e);            }        });        httpClient.executeAsync(request);    }    public void post(String url, String jsonParam, final HttpResponseListener responseListener) {        SLog.Console("请求url=   " + url);        SLog.Console("请求Request" + jsonParam);        final StringRequest request = new StringRequest(url).setMethod(HttpMethods.Post);        LinkedHashMap<String, String> headers = new LinkedHashMap<String, String>();        headers.put("Token", MainApplication.getInstance().getToken());        headers.put("DeviceId", MainApplication.getInstance().getDeviceId());        request.setHeaders(headers);        request.setHttpBody(new JsonBody(jsonParam));        request.setHttpListener(new HttpListener<String>() {            @Override            public void onSuccess(String res, Response<String> response) {                SLog.Console("返回response " + res);                BaseResponseEntity<JSONObject> bre = JsonUtils.json2Class(res, new BaseResponseEntity<JSONObject>().getClass());                // 成功不进行校验 只校验 2003 TOKEN失效情况                if ("2003".equals(bre.getCode())) {                    Intent intent = new Intent();                    intent.setAction(ServiceConstant.INTENT_ACTION_CLOSEALL);                    appContext.sendBroadcast(intent);                    appContext.stopService(new Intent(appContext, HeartbeatService.class));                }                responseListener.onSuccess(response.getHttpStatus().getCode() + "", res);            }            @Override            public void onFailure(HttpException e, Response<String> response) {                if (e != null && !TextUtils.isEmpty(e.getMessage()) && e.getMessage().contains("Network Is Not Avilable"))  {                    responseListener.onSuccess(HttpConstant.HTTP_SUCCESS, "{\"code\": -1, \"message\":\"连接服务器失败,请验证网络情况\"}");                } else {                    responseListener.onFailure(e);                }            }        });        httpClient.executeAsync(request);    }    public void postUpload(String url, File file, final HttpResponseListener responseListener) {        SLog.Console("请求url=   " + url);        SLog.Console("请求Request" + file.getName());        final StringRequest request = new StringRequest(url).setMethod(HttpMethods.Post);        LinkedHashMap<String, String> headers = new LinkedHashMap<String, String>();        headers.put("Token", MainApplication.getInstance().getToken());        headers.put("DeviceId", MainApplication.getInstance().getDeviceId());        request.setHeaders(headers);        request.setHttpBody(new FileBody(file));        request.setHttpListener(new HttpListener<String>() {            @Override            public void onSuccess(String res, Response<String> response) {                SLog.Console("返回response " + res);                BaseResponseEntity<JSONObject> bre = JsonUtils.json2Class(res, new BaseResponseEntity<JSONObject>().getClass());                // 成功不进行校验 只校验 2003 TOKEN失效情况                if ("2003".equals(bre.getCode())) {                    Intent intent = new Intent();                    intent.setAction(ServiceConstant.INTENT_ACTION_CLOSEALL);                    appContext.sendBroadcast(intent);                    appContext.stopService(new Intent(appContext, HeartbeatService.class));                }                responseListener.onSuccess(response.getHttpStatus().getCode() + "", res);            }            @Override            public void onFailure(HttpException e, Response<String> response) {                if (e != null && !TextUtils.isEmpty(e.getMessage()) && e.getMessage().contains("Network Is Not Avilable"))  {                    responseListener.onSuccess(HttpConstant.HTTP_SUCCESS, "{\"code\": -1, \"message\":\"连接服务器失败,请验证网络情况\"}");                } else {                    responseListener.onFailure(e);                }            }        });        httpClient.executeAsync(request);    }    public void loadFile(String url, String saveToPath, final HttpResponseListener responseListener) {        httpClient.executeAsync(new FileRequest(url, saveToPath).setHttpListener(new HttpListener<File>(true, true, true) {            @Override            public void onLoading(AbstractRequest<File> request, long total, long len) {            }            @Override            public void onSuccess(File file, Response<File> response) {                responseListener.onSuccess(response.getHttpStatus().getCode() + "", "");            }            @Override            public void onFailure(HttpException error, Response<File> response) {                responseListener.onFailure(error);            }        }));    }}
// 常量public class HttpConstant {    // 业务结果成功    public final static String BUSINESS_SUCCESS = "0";    // 网络请求结果成功    public final static String HTTP_SUCCESS = "200";}
public class HttpResponseListener implements IHttpResponseListener{    @Override    public void onFailure(Throwable error) {    }    @Override    public void onSuccess(String status, String result) {    }}
public interface IHttpResponseListener {    void onFailure(Throwable error);    void onSuccess(String statusCode, String result);}

与业务相关的代码就不贴出来了,有时间在做完善吧

1 0
原创粉丝点击