Android网络框架AsyncHttpClient的二次封装

Android中网络请求一般使用Apache HTTP Client或者采用HttpURLConnect,但是直接使用这两个类库需要写大量的代码才能完成网络post和get请求,而使用Android-Async-Http这个库可以大大的简化操作,它是基于Apache’s HttpClient ,所有的请求都是独立在UI主线程之外,通过回调方法处理请求结果,采用Android  Handler Message 机制传递信息。

Android-Async-Http特性
1)采用异步http请求,并通过匿名内部类处理回调结果
2)http请求独立在UI主线程之外
3)采用线程池来处理并发请求
4)采用RequestParams类创建GET/POST参数
5)不需要第三方包即可支持Multipart file文件上传
6)大小只有25kb
7)自动为各种移动电话处理连接断开时请求重连
8)超快的自动gzip响应解码支持
9)使用BinaryHttpResponseHandler类下载二进制文件(如图片)
10) 使用JsonHttpResponseHandler类可以自动将响应结果解析为json格式
11)持久化cookie存储,可以将cookie保存到你的应用程序的SharedPreferences中


今天以Android-Async-Http这个库为演示,进行网络框架的二次封装,二次封装优势很明显,譬如易于项目后期修改网络框架等等。


下来看二次封装具体实现的流程图和代码实现:

Android网络框架AsyncHttpClient的二次封装_第1张图片

1.在AppContext中初始化网络请求,将框架封装到ApiHttpClient

package com.example.network;

import android.app.Application;

import com.example.network.api.ApiHttpClient;
import com.loopj.android.http.AsyncHttpClient;

public class AppContext extends Application {

	@Override
	public void onCreate() {
		super.onCreate();
		
		init();
	}

	private void init() {
        // 初始化网络请求
        AsyncHttpClient client = new AsyncHttpClient();
        
        // 将框架封装到ApiHttpClient
        ApiHttpClient.setHttpClient(client);
	}
	
}

千万注意要加上网络权限:

    

    


2.封装的ApiHttpClient拥有网络请求的能力,并且封装了请求主机

package com.example.network.api;

import java.util.Locale;

import org.apache.http.client.params.ClientPNames;

import android.content.Context;
import android.util.Log;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public class ApiHttpClient {

    public final static String HOST = "www.google.com";
    private static String API_URL = "http://www.google.com/%s";
    
    public final static String HOST_LOCAL = "192.168.52.2";
    private static String API_URL_LOCAL = "http://192.168.52.2:8080/%s";
    
    // public final static String HOST = "192.168.52.2";
    // private static String API_URL = "http://192.168.52.2/%s";
    public static final String DELETE = "DELETE";
    public static final String GET = "GET";
    public static final String POST = "POST";
    public static final String PUT = "PUT";
    public static AsyncHttpClient client;

    public ApiHttpClient() {}

    public static AsyncHttpClient getHttpClient() {
        return client;
    }

    public static void cancelAll(Context context) {
        client.cancelRequests(context, true);
    }

    public static void clearUserCookies(Context context) {
        // (new HttpClientCookieStore(context)).a();
    }

    public static void delete(String partUrl, AsyncHttpResponseHandler handler) {
        client.delete(getAbsoluteApiUrl(partUrl), handler);
        log(new StringBuilder("DELETE ").append(partUrl).toString());
    }

    public static void get(String partUrl, AsyncHttpResponseHandler handler) {
        client.get(getAbsoluteApiUrl(partUrl), handler);
        log(new StringBuilder("GET ").append(partUrl).toString());
    }

    public static void get(String partUrl, RequestParams params,
            AsyncHttpResponseHandler handler) {
        client.get(getAbsoluteApiUrl(partUrl), params, handler);
        log(new StringBuilder("GET ").append(partUrl).append("&")
                .append(params).toString());
    }

    /**
     * 获取局域网服务器数据
     * @param partUrl
     * @param params
     * @param handler
     */
    public static void getLocal(String partUrl, AsyncHttpResponseHandler handler) {
        client.get(getLocalAbsoluteApiUrl(partUrl), handler);
        log(new StringBuilder("GET ").append(partUrl).toString());
    }

    /**
     * 获取局域网服务器数据
     * @param partUrl
     * @param params
     * @param handler
     */
    public static void getLocal(String partUrl, RequestParams params,
    		AsyncHttpResponseHandler handler) {
    	client.get(getLocalAbsoluteApiUrl(partUrl), params, handler);
    	log(new StringBuilder("GET ").append(partUrl).append("&")
    			.append(params).toString());
    }
    
    public static String getLocalAbsoluteApiUrl(String partUrl) {
        String url = String.format(API_URL_LOCAL, partUrl);
        Log.d("BASE_CLIENT", "request:" + url);
        return url;
    }

    public static String getAbsoluteApiUrl(String partUrl) {
        String url = String.format(API_URL, partUrl);
        Log.d("BASE_CLIENT", "request:" + url);
        return url;
    }

    public static String getApiUrl() {
        return API_URL;
    }

    public static void getDirect(String url, AsyncHttpResponseHandler handler) {
        client.get(url, handler);
        log(new StringBuilder("GET ").append(url).toString());
    }

    public static void log(String log) {
        Log.d("BaseApi", log);
    }

    public static void post(String partUrl, AsyncHttpResponseHandler handler) {
        client.post(getAbsoluteApiUrl(partUrl), handler);
        log(new StringBuilder("POST ").append(partUrl).toString());
    }

    public static void post(String partUrl, RequestParams params,
            AsyncHttpResponseHandler handler) {
        client.post(getAbsoluteApiUrl(partUrl), params, handler);
        log(new StringBuilder("POST ").append(partUrl).append("&")
                .append(params).toString());
    }

    public static void postDirect(String url, RequestParams params,
            AsyncHttpResponseHandler handler) {
        client.post(url, params, handler);
        log(new StringBuilder("POST ").append(url).append("&").append(params)
                .toString());
    }

    public static void put(String partUrl, AsyncHttpResponseHandler handler) {
        client.put(getAbsoluteApiUrl(partUrl), handler);
        log(new StringBuilder("PUT ").append(partUrl).toString());
    }

    public static void put(String partUrl, RequestParams params,
            AsyncHttpResponseHandler handler) {
        client.put(getAbsoluteApiUrl(partUrl), params, handler);
        log(new StringBuilder("PUT ").append(partUrl).append("&")
                .append(params).toString());
    }

    public static void setApiUrl(String apiUrl) {
        API_URL = apiUrl;
    }

    /**
     * 初始化请求头
     */
    public static void setHttpClient(AsyncHttpClient c) {
        client = c;
        client.addHeader("Accept-Language", Locale.getDefault().toString());
        client.addHeader("Host", HOST);
        client.addHeader("Connection", "Keep-Alive");
        client.getHttpClient().getParams()
                .setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);

    }

    public static void setUserAgent(String userAgent) {
        client.setUserAgent(userAgent);
    }

    public static void setCookie(String cookie) {
        client.addHeader("Cookie", cookie);
    }

    private static String appCookie;

    public static void cleanCookie() {
        appCookie = "";
    }

}

3.为了更方便的调用ApiHttpClientNetWorkApi封装了请求路径、参数,而当请求网络时,只需要调用NetWorkApi,将请求参数传入即可

package com.example.network.api;

import android.text.TextUtils;

import com.loopj.android.http.AsyncHttpResponseHandler;

public class NetWorkApi {

	/**
	 * 根据用户 指定的类型, 页码 请求数据. 
	 * @param catalog
	 * @param page
	 * @param handler 传给框架, 当数据请求结束时, 里边的方法会被调用
	 */
	public static void getNewsList(int catalog, int page,
			AsyncHttpResponseHandler handler) {

		// 测试地址:http://192.168.52.2:8080/networkserver/list/news/page0.xml
		String path = "";
		switch (catalog) {
		case 1:
			path = "networkserver/list/news/page"+page+".xml";
			break;
		case 4:
			path = "networkserver/list/hotspot/page"+page+".xml";
			break;
		default:
			break;
		}
		if(TextUtils.isEmpty(path)) return;
		
		ApiHttpClient.getLocal("networkserver/list/news/page"+page+".xml", handler);
	}

}


4.MainActivity将请求参数传入NetWorkApi,并将请求成功的字符串显示在Demo界面上

package com.example.network;

import org.apache.http.Header;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.example.network.api.NetWorkApi;
import com.example.network.R;
import com.loopj.android.http.AsyncHttpResponseHandler;

public class MainActivity extends Activity {

	private int page;
	private int catalog;
	private TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        tv = (TextView) findViewById(R.id.tv);
    }

    public void getData(View view){
    	// 请求一个网络地址, 将字符串显示到界面上
    	// 测试地址:http://192.168.52.2:8080/networkserver/list/news/page0.xml
    	
    	/**
    	 * 请求网络:一行代码实现
    	 */
    	page = 0; // 第几页
    	catalog = 1;
		NetWorkApi.getNewsList(catalog, page, handler);

    }
    
    AsyncHttpResponseHandler handler = new AsyncHttpResponseHandler() {
    	@Override
    	public void onSuccess(int code, Header[] headers, byte[] data) {
    		Toast.makeText(getApplicationContext(), "请求成功", 0).show();
    		tv.setText(new String(data));
    	}
    	@Override
    	public void onFailure(int code, Header[] arg1, byte[] arg2, Throwable arg3) {
    		Toast.makeText(getApplicationContext(), "请求失败", 0).show();
    	}
    };
    
}

二次封装后的运行效果图:

Android网络框架AsyncHttpClient的二次封装_第2张图片


项目源码,点击下载


转载于:https://www.cnblogs.com/smartbetter/p/6647523.html

你可能感兴趣的:(Android网络框架AsyncHttpClient的二次封装)