android-async-http 封装

Posted wlytctw

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了android-async-http 封装相关的知识,希望对你有一定的参考价值。

概要

在 2013年之前这个网络请求库还是不错!随着技术的更新,这个逐渐被放弃使用!接近年关,更多的是闲暇无事,看到老项目中在使用网络请求并没有为此做二次封装,在接口回调当中写下了很多Json解析等其他的逻辑为此,简单的封装了改网络请求!并统一的管理Gson数据的处理。

介绍

  • 本示例Demo 封装了get/post(文件上传)等等····
  • 统一的异常管理
  • 虽然说 android-async-http 这个网络请求库,本人已经不再使用了,但是可以学习当中
    的设计思想和编码规范。为此做出封装。
  • 针对这个框架的思想,自己做的请求框架,可以参考了解。地址:https://github.com/wanglyGithub/AsynHttpClient

层次结构

AsyncHttpUtils 代码

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.util.Map;

import cz.msebera.android.httpclient.Header;

public class AsyncHttpUtils 
    private static AsyncHttpUtils instance;
    private AsyncHttpClient httpClient;
    private RequestParams requestParams;
    private static final int TIME_OUT = 1000;
    private static final int MAX_CONNECT_TIME = 1000;
    private final Gson gson;

    private AsyncHttpUtils() 
        httpClient = new AsyncHttpClient();
        httpClient.setTimeout(TIME_OUT);
        httpClient.setMaxConnections(MAX_CONNECT_TIME);

        gson = new Gson();


    

    public static AsyncHttpUtils getInstance() 
        if (instance == null) 
            instance = new AsyncHttpUtils();
        
        return instance;
    

    /**
     * GET
     *
     * @param url
     * @param callBack
     */
    public void get(String url, ResultCallBack callBack) 
        httpClient.get(url, new HttpResponseHandler(callBack));

    

    /**
     * GET
     *
     * @param url
     * @param params
     * @param callback
     */
    public void get(String url, Map<String, Object> params, ResultCallBack callback) 
        RequestParams requestParams = doRequestParams(params);
        httpClient.get(url, requestParams, new HttpResponseHandler(callback));
    


    /**
     * POST
     *
     * @param url
     * @param params
     * @param callback
     */
    public void post(String url, Map<String, Object> params, final ResultCallBack callback) 
        RequestParams requestParams = doRequestParams(params);
        httpClient.post(url, requestParams, new HttpResponseHandler(callback));

    


    public RequestParams doRequestParams(Map<String, Object> params) 
        requestParams = new RequestParams();
        for (Map.Entry<String, Object> entry : params.entrySet()) 
            requestParams.put(entry.getKey(), entry.getValue());
        
        return requestParams;
    


    // exectue AsyncHttpClient
    class HttpResponseHandler extends AsyncHttpResponseHandler 
        private ResultCallBack callBack;

        public HttpResponseHandler(ResultCallBack back) 
            this.callBack = back;

        

        @Override
        public void onStart() 
            super.onStart();
            if (callBack != null) 
                callBack.onStart();
            
        

        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) 
            if (statusCode == 200) 
                String result = new String(responseBody);
                if (!"".equals(result) && null != result) 
                    if (result.startsWith("\\uFEFF")) 
                        result = result.substring(1, result.length());
                    

                    if (callBack.mType == String.class) 
                        doSuccess(callBack, statusCode, result);
                     else 
                        try 
                            Object object = gson.fromJson(result, callBack.mType);
                            if (callBack != null) 
                                doSuccess(callBack, statusCode, object);
                            
                         catch (JsonSyntaxException e) 
                            e.printStackTrace();
                            ApiException.getApiExceptionMessage(e.getCause());
                        

                    
                

            
        

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) 
            doFailed(callBack, statusCode, error);
        
    


    public void doSuccess(ResultCallBack callBack, int stateCode, Object object) 
        if (callBack != null) 
            callBack.Success(stateCode, object);
        
    

    public void doFailed(ResultCallBack callBack, int errorCode, Throwable throwable) 
        if (callBack != null) 
            callBack.Failure(errorCode, ApiException.getApiExceptionMessage(throwable));
        
    


    // 其他类型,不在封装,
    // 如:追踪源码可知:JsonHttpResponseHandler 是 AsyncHttpResponseHandler 的子类
    // 所以可以共用 同一个,但是需要进行转型
    //以下提供了枚举类型,可供参考,封装

    enum OtherType 
        down_json,
        down_byte
    



ApiException 异常管理

import com.google.gson.JsonParseException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import cz.msebera.android.httpclient.client.HttpResponseException;

/**
 *
 * @description 描述: 异常管理类
 */

public class ApiException 
    public static final String NET_WORK_ERROR = "网络不可用";
    public static final String CONNECT_EXCEPTION = "网络不给力,请稍后重试";
    public static final String SERVER_ADDRES_ERROR = "URL 地址有误!";
    public static final String JSON_PARSE_ERROR = "Json 解析出错";

    public static String getApiExceptionMessage(Throwable throwable) 
        if (throwable instanceof UnknownHostException || throwable instanceof ConnectException) 
            return NET_WORK_ERROR;
         else if (throwable instanceof SocketTimeoutException) 
            return CONNECT_EXCEPTION;
         else if (throwable instanceof HttpResponseException) 
            return SERVER_ADDRES_ERROR;
         else if (throwable instanceof JsonParseException) 
            return JSON_PARSE_ERROR;
         else 
            return "未知错误";
        
    

ResultCallBack

import com.google.gson.internal.$Gson$Types;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public abstract class ResultCallBack<T> 

    public Type mType;

    static Type getSuperclassTypeParameter(Class<?> subclass) 
        Type superclass = subclass.getGenericSuperclass();
        if (superclass instanceof Class) 
            throw new RuntimeException("Missing type parameter.");
        
        ParameterizedType parameterized = (ParameterizedType) superclass;
        return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]);
    


    public ResultCallBack () 
        mType = getSuperclassTypeParameter(getClass());
    

    public abstract void onStart();

    public abstract void Success(int statusCode, T t);

    public abstract void Failure(int errorCode, String exception);


最后演示

以上是关于android-async-http 封装的主要内容,如果未能解决你的问题,请参考以下文章

Android-async-http 的用法

android-async-http框架源码分析

android-async-http框架

心流 - 闲暇时间

基于android-async-http的android服务

利用loopj的android-async-http进行文件上传