码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2017-06-09 11:51:01      阅读:311      评论:0      收藏:0      [点我收藏+]

标签:扩展   定义   版本   detail   ring   cal   stack   源代码下载   bsp   

    网络请求是全部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功能都具备了,假设开发中遇到一些特殊的功能,可能再依据详细的需求扩展。


    源代码下载

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

标签:扩展   定义   版本   detail   ring   cal   stack   源代码下载   bsp   

原文地址:http://www.cnblogs.com/gccbuaa/p/6971262.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!