android基于开源网络框架asychhttpclient,二次封装为通用网络请求组件

    网络请求是所有App都必不可少的功能,如果每次开发都重写一次网络请求或者将以前的代码复制到新的App中,不是很合理,出于此目的,我希望将整个网络请求框架独立出来,与业务逻辑分隔开,这样就可以避免每次都要重新编写网络请求,于是基于我比较熟悉的asynchttpclient重新二次封装了一个网络请求框架。

   思路:网络请求层唯一的功能就是发送请求,接收响应数据,请求取消,cookie处理这几个功能,二次助封装后这些功能可以直接调用封装好的方法即可。

   二次助封装代码如下:

   1.功能接口:

/**********************************************************
 * @文件名称:DisposeDataListener.java
 * @文件作者:rzq
 * @创建时间:2015年8月19日 上午11:01:13
 * @文件描述:
 * @修改历史:2015年8月19日创建初始版本
 **********************************************************/
public interface DisposeDataListener
{
    /**
     * 请求开始回调事件处理
     */
    public void onStart();

    /**
     * 请求成功回调事件处理
     */
    public void onSuccess(Object responseObj);

    /**
     * 请求失败回调事件处理
     */
    public void onFailure(Object reasonObj);

    /**
     * 请求重连回调事件处理
     */
    public void onRetry(int retryNo);

    /**
     * 请求进度回调事件处理
     */
    public void onProgress(long bytesWritten, long totalSize);

    /**
     * 请求结束回调事件处理
     */
    public void onFinish();

    /**
     * 请求取消回调事件处理
     */
    public void onCancel();
}


   2.请求功能接口适配器模式

public class DisposeDataHandle implements DisposeDataListener
{
    @Override
    public void onStart()
    {
    }

    @Override
    public void onSuccess(Object responseObj)
    {
    }

    @Override
    public void onFailure(Object reasonObj)
    {
    }

    @Override
    public void onRetry(int retryNo)
    {
    }

    @Override
    public void onProgress(long bytesWritten, long totalSize)
    {
    }

    @Override
    public void onFinish()
    {
    }

    @Override
    public void onCancel()
    {
    }
}

   3.请求回调事件处理:   

/**********************************************************
 * @文件名称:BaseJsonResponseHandler.java
 * @文件作者:rzq
 * @创建时间:2015年8月19日 上午10:41:46
 * @文件描述:服务器Response基础类,包括了java层异常和业务逻辑层异常码定义
 * @修改历史:2015年8月19日创建初始版本
 **********************************************************/
public class BaseJsonResponseHandler extends JsonHttpResponseHandler
{
    /**
     * the logic layer exception, may alter in different app
     */
    protected final String RESULT_CODE = "ecode";
    protected final int RESULT_CODE_VALUE = 0;
    protected final String ERROR_MSG = "emsg";
    protected final String EMPTY_MSG = "";

    /**
     * the java layer exception
     */
    protected final int NETWORK_ERROR = -1; // the network relative error
    protected final int JSON_ERROR = -2; // the JSON relative error
    protected final int OTHER_ERROR = -3; // the unknow error

    /**
     * interface and the handle class
     */
    protected Class<?> mClass;
    protected DisposeDataHandle mDataHandle;

    public BaseJsonResponseHandler(DisposeDataHandle dataHandle, Class<?> clazz)
    {
        this.mDataHandle = dataHandle;
        this.mClass = clazz;
    }

    public BaseJsonResponseHandler(DisposeDataHandle dataHandle)
    {
        this.mDataHandle = dataHandle;
    }

    /**
     * only handle the success branch(ecode == 0)
     */
    public void onSuccess(JSONObject response)
    {
    }

    /**
     * handle the java exception and logic exception branch(ecode != 0)
     */
    public void onFailure(Throwable throwObj)
    {
    }

    @Override
    public void onSuccess(int statusCode, Header[] headers, JSONObject response)
    {
        onSuccess(response);
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse)
    {
        onFailure(throwable);
    }
}

/**********************************************************
 * @文件名称:CommonJsonResponseHandler.java
 * @文件作者:rzq
 * @创建时间:2015年8月19日 上午11:01:13
 * @文件描述:业务逻辑层真正处理的地方,包括java层异常和业务层异常
 * @修改历史:2015年8月19日创建初始版本
 **********************************************************/
public class CommonJsonResponseHandler extends BaseJsonResponseHandler
{
    public CommonJsonResponseHandler(DisposeDataHandle dataHandle)
    {
        super(dataHandle);
    }

    public CommonJsonResponseHandler(DisposeDataHandle dataHandle, Class<?> clazz)
    {
        super(dataHandle, clazz);
    }

    @Override
    public void onStart()
    {
        mDataHandle.onStart();
    }

    @Override
    public void onProgress(long bytesWritten, long totalSize)
    {
        mDataHandle.onProgress(bytesWritten, totalSize);
    }

    @Override
    public void onSuccess(JSONObject response)
    {
        handleResponse(response);
    }

    @Override
    public void onFailure(Throwable throwObj)
    {
        mDataHandle.onFailure(new LogicException(NETWORK_ERROR, throwObj.getMessage()));
    }

    @Override
    public void onCancel()
    {
        mDataHandle.onCancel();
    }

    @Override
    public void onRetry(int retryNo)
    {
        mDataHandle.onRetry(retryNo);
    }

    @Override
    public void onFinish()
    {
        mDataHandle.onFinish();
    }

    /**
     * handle the server response
     */
    private void handleResponse(JSONObject response)
    {
        if (response == null)
        {
            mDataHandle.onFailure(new LogicException(NETWORK_ERROR, EMPTY_MSG));
            return;
        }

        try
        {
            if (response.has(RESULT_CODE))
            {
                if (response.optInt(RESULT_CODE) == RESULT_CODE_VALUE)
                {
                    if (mClass == null)
                    {
                        mDataHandle.onSuccess(response);
                    }
                    else
                    {
                        Object obj = ResponseEntityToModule.parseJsonObjectToModule(response, mClass);
                        if (obj != null)
                        {
                            mDataHandle.onSuccess(obj);
                        }
                        else
                        {
                            mDataHandle.onFailure(new LogicException(JSON_ERROR, EMPTY_MSG));
                        }
                    }
                }
                else
                {
                    if (response.has(ERROR_MSG))
                    {
                        mDataHandle.onFailure(new LogicException(response.optInt(RESULT_CODE), response
                                .optString(ERROR_MSG)));
                    }
                    else
                    {
                        mDataHandle.onFailure(new LogicException(response.optInt(RESULT_CODE), EMPTY_MSG));
                    }
                }
            }
            else
            {
                if (response.has(ERROR_MSG))
                {
                    mDataHandle.onFailure(new LogicException(OTHER_ERROR, response.optString(ERROR_MSG)));
                }
            }
        }
        catch (Exception e)
        {
            mDataHandle.onFailure(new LogicException(OTHER_ERROR, e.getMessage()));
            e.printStackTrace();
        }
    }
}

  4.自定义异常类,对java异常和业务逻辑异常封装统一处理

/**********************************************************
 * @文件名称:LogicException.java
 * @文件作者:rzq
 * @创建时间:2015年8月19日 上午10:05:08
 * @文件描述:自定义异常类,返回ecode,emsg到业务层
 * @修改历史:2015年8月19日创建初始版本
 **********************************************************/
public class LogicException extends Exception
{
	private static final long serialVersionUID = 1L;

	/**
	 * the server return code
	 */
	private int ecode;

	/**
	 * the server return error message
	 */
	private String emsg;

	public LogicException(int ecode, String emsg)
	{
		this.ecode = ecode;
		this.emsg = emsg;
	}

	public int getEcode()
	{
		return ecode;
	}

	public String getEmsg()
	{
		return emsg;
	}
}
   5.请求发送入口类CommonClient:
/**********************************************************
 * @文件名称:CommonClient.java
 * @文件作者:rzq
 * @创建时间:2015年8月19日 上午11:38:57
 * @文件描述:通用httpclient,支持重连,取消请求,Cookie存储
 * @修改历史:2015年8月19日创建初始版本
 **********************************************************/
public class CommonClient
{
	private static AsyncHttpClient client;
	static
	{
		/**
		 * init the retry exception
		 */
		AsyncHttpClient.allowRetryExceptionClass(IOException.class);
		AsyncHttpClient.allowRetryExceptionClass(SocketTimeoutException.class);
		AsyncHttpClient.allowRetryExceptionClass(ConnectTimeoutException.class);
		/**
		 * init the block retry exception
		 */
		AsyncHttpClient.blockRetryExceptionClass(UnknownHostException.class);
		AsyncHttpClient.blockRetryExceptionClass(ConnectionPoolTimeoutException.class);

		client = new AsyncHttpClient();
	}

	public static RequestHandle get(String url, AsyncHttpResponseHandler responseHandler)
	{
		return client.get(url, responseHandler);
	}

	public static RequestHandle get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler)
	{
		return client.get(url, params, responseHandler);
	}

	public static RequestHandle get(Context context, String url, AsyncHttpResponseHandler responseHandler)
	{
		return client.get(context, url, responseHandler);
	}

	public static RequestHandle get(Context context, String url, RequestParams params,
			AsyncHttpResponseHandler responseHandler)
	{
		return client.get(context, url, params, responseHandler);
	}

	public static RequestHandle get(Context context, String url, Header[] headers, RequestParams params,
			AsyncHttpResponseHandler responseHandler)
	{
		return client.get(context, url, headers, params, responseHandler);
	}

	public static RequestHandle post(String url, AsyncHttpResponseHandler responseHandler)
	{
		return client.post(url, responseHandler);
	}

	public static RequestHandle post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler)
	{
		return client.post(url, params, responseHandler);
	}

	public static RequestHandle post(Context context, String url, RequestParams params,
			AsyncHttpResponseHandler responseHandler)
	{
		return client.post(context, url, params, responseHandler);
	}

	public static RequestHandle post(Context context, String url, HttpEntity entity, String contentType,
			AsyncHttpResponseHandler responseHandler)
	{
		return client.post(context, url, entity, contentType, responseHandler);
	}

	public static RequestHandle post(Context context, String url, Header[] headers, RequestParams params,
			String contentType, AsyncHttpResponseHandler responseHandler)
	{
		return client.post(context, url, headers, params, contentType, responseHandler);
	}

	public static RequestHandle post(Context context, String url, Header[] headers, HttpEntity entity,
			String contentType, AsyncHttpResponseHandler responseHandler)
	{
		return client.post(context, url, headers, entity, contentType, responseHandler);
	}

	/**
	 * calcel the context relative request
	 * @param context
	 * @param mayInterruptIfRunning
	 */
	public void calcelRequests(Context context, boolean mayInterruptIfRunning)
	{
		client.cancelRequests(context, mayInterruptIfRunning);
	}

	/**
	 * cancel current all request in app
	 * @param mayInterruptIfRunning
	 */
	public void cacelAllrequests(boolean mayInterruptIfRunning)
	{
		client.cancelAllRequests(mayInterruptIfRunning);
	}

	public static void setHttpContextAttribute(String id, Object obj)
	{
		client.getHttpContext().setAttribute(id, obj);
	}

	public static Object getHttpContextAttribute(String id)
	{
		return client.getHttpContext().getAttribute(id);
	}

	public static void removeHttpContextAttribute(String id)
	{
		client.getHttpContext().removeAttribute(id);
	}

	/**
	 * set the cookie store
	 * @param cookieStore
	 */
	public static void setCookieStore(CookieStore cookieStore)
	{
		client.setCookieStore(cookieStore);
	}

	/**
	 * remove the cookie store
	 */
	public static void removeCookieStore()
	{
		removeHttpContextAttribute(ClientContext.COOKIE_STORE);
	}
}

     6.登陆DEMO使用

     Cookie的保存,   

public class MyApplicaton extends Application {
	private static MyApplicaton app;

	@Override
	public void onCreate() {
		super.onCreate();
		app = this;
		/**
		 * 为全局 CommonClient添加CookieStore,从PersistentCookieStore中可以拿出所有Cookie
		 */
		CommonClient.setCookieStore(new PersistentCookieStore(this));
	}

	public static MyApplicaton getInstance() {
		return app;
	}
}

     响应体的处理:

   private void requestLogin()
	{
		RequestParams params = new RequestParams();
		params.put("mb", "");
		params.put("pwd", "");
		CommonClient.post(this, URL, params, new CommonJsonResponseHandler(
				new DisposeDataHandle()
				{
					@Override
					public void onSuccess(Object responseObj)
					{
						Log.e("------------->", responseObj.toString());
						
					}

					@Override
					public void onFailure(Object reasonObj)
					{
						Log.e("----->", ((LogicException)reasonObj).getEmsg());
					}

					@Override
					public void onProgress(long bytesWritten, long totalSize)
					{
						Log.e("------------->", bytesWritten + "/" + totalSize);
					}
				}));
	}

    经过以上封装后,基于的http功能都具备了,如果开发中遇到一些特殊的功能,可能再根据具体的需求扩展。
    源码下载

猜你喜欢

转载自blog.csdn.net/lcq5211314123/article/details/47805855