Android-async-http 网络请求框架(工具类)

满雨石
2023-12-01

Android-async-http仓库:https://github.com/loopj/android-async-http
android-async-http主页:http://loopj.com/android-async-http/
大牛讲解地址:http://blog.csdn.net/yanbober/article/details/45307549

android-async-http的特性:

    发送异步http请求,在匿名callback对象中处理response信息;

    http请求发生在UI(主)线程之外的异步线程中;

    内部采用线程池来处理并发请求;

    通过RequestParams类构造GET/POST;

    内置多部分文件上传,不需要第三方库支持;

    流式Json上传,不需要额外的库;

    能处理环行和相对重定向;

    和你的app大小相比来说,库的size很小,所有的一切只有90kb;

    在各种各样的移动连接环境中具备自动智能请求重试机制;

    自动的gzip响应解码;

    内置多种形式的响应解析,有原生的字节流,string,json对象,甚至可以将response写到文件中;

    永久的cookie保存,内部实现用的是Android的SharedPreferences;

    通过BaseJsonHttpResponseHandler和各种json库集成;

    支持SAX解析器;

    支持各种语言和content编码,不仅仅是UTF-8;
===================================================
    RequestParams的基础使用

    RequestParams params = new RequestParams();
    params.put("username", "yanbober");
    params.put("password", "123456");
    params.put("email", "yanbobersky@email.com");

    /*
    * Upload a File
    */
    params.put("file_pic", new File("test.jpg"));
    params.put("file_inputStream", inputStream);
    params.put("file_bytes", new ByteArrayInputStream(bytes));

    /*
    * url params: "user[first_name]=jesse&user[last_name]=yan"
    */
    Map<String, String> map = new HashMap<String, String>();
    map.put("first_name", "jesse");
    map.put("last_name", "yan");
    params.put("user", map);

    /*
    * url params: "what=haha&like=wowo"
    */
    Set<String> set = new HashSet<String>();
    set.add("haha");
    set.add("wowo");
    params.put("what", set);

    /*
    * url params: "languages[]=Java&languages[]=C"
    */
    List<String> list = new ArrayList<String>();
    list.add("Java");
    list.add("C");
    params.put("languages", list);

    /*
    * url params: "colors[]=blue&colors[]=yellow"
    */
    String[] colors = { "blue", "yellow" };
    params.put("colors", colors);

    /*
    * url params: "users[][age]=30&users[][gender]=male&users[][age]=25&users[][gender]=female"
    */
    List<Map<String, String>> listOfMaps = new ArrayList<Map<String, String>>();
    Map<String, String> user1 = new HashMap<String, String>();
    user1.put("age", "30");
    user1.put("gender", "male");

    Map<String, String> user2 = new HashMap<String, String>();
    user2.put("age", "25");
    user2.put("gender", "female");

    listOfMaps.add(user1);
    listOfMaps.add(user2);

    params.put("users", listOfMaps);

    /*
    * 使用实例
    */
    AsyncHttpClient client = new AsyncHttpClient();
    client.post("http://localhost:8080/androidtest/", params, responseHandler);
        ========================
    * RequestParams params = new RequestParams();
    * params.put("username", "james");
    * params.put("password", "123456");
    * params.put("email", "my@email.com");
    * params.put("profile_picture", new File("pic.jpg")); // Upload a File
    * params.put("profile_picture2", someInputStream); // Upload an InputStream
    * params.put("profile_picture3", new ByteArrayInputStream(someBytes)); // Upload some bytes
=======================================

贴上自己封装的一个简易工具类:

import java.util.Map;
import org.xutils.common.util.LogUtil;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.BinaryHttpResponseHandler;
import com.loopj.android.http.FileAsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.ResponseHandlerInterface;

import android.content.Context;

/**
 *android-async-http 网络请求封装工具类
 */
public class AndroidAsyncHttpUtils {
    private static AndroidAsyncHttpUtils instance;
    private static AsyncHttpClient asyncHttpClient;
    public static String ANDROID_ASYNC_HTTP_GET_REQUEST="Android_Async_Http_Utils_Get_Request";
    public static String ANDROID_ASYNC_HTTP_POST_REQUEST="Android_Async_Http_Utils_Post_Request";
    public static String ANDROID_ASYNC_HTTP_PUT_REQUEST="Android_Async_Http_Utils_Put_Request";
    public static AndroidAsyncHttpUtils getInstance(){
        if(instance==null){
            synchronized (AndroidAsyncHttpUtils.class) {
                if(instance==null){
                    instance=new AndroidAsyncHttpUtils();
                }
            }
        }
        if(asyncHttpClient==null){
            asyncHttpClient=new AsyncHttpClient();
            asyncHttpClient.setTimeout(10000);//默认为10s 
        }
        return instance;
    }
    /**
     * url 带参数访问网络  请求string类型 ,可上传图片,文件
     * @param method  
     * <p/>
     *    ANDROID_ASYNC_HTTP_GET_REQUEST ,
     *    <p/>
     *    ANDROID_ASYNC_HTTP_POST_REQUEST,
     *    <p/>
     *    ANDROID_ASYNC_HTTP_PUT_REQUEST
     * @param path
     * @param map (string int ..) 可以为null
     * @param callback  ResponseHandlerInterface 
     * <p/>
     * AsyncHttpResponseHandler 用于string结果类型 
     * <p/>
     * BinaryHttpResponseHandler 用于下载 
     * <p/>
     * JsonHttpResponseHandler 用于请求json结果  
     * <p/>
     * FileAsyncHttpResponseHandler 用于file类型
     */
    public void StartAndroidAsyncHttpRequest(String method,String path,Map<String,Object>map,ResponseHandlerInterface callback){
        Network(method, path, map, callback);
    }
    /**
     * 取消全部请求
     * @param context
     * @param mayInterruptIfRunning
     */
    public void CancelAndroidAsyncHttpRequest(Context context,boolean mayInterruptIfRunning){
        asyncHttpClient.cancelRequests(context, mayInterruptIfRunning);
    }
    /**
     * 联网发请求
     * @param method
     * @param path
     * @param map
     * @param callback
     */
    private void Network(String method, String path, Map<String, Object> map, ResponseHandlerInterface callback) {
        RequestParams requestParams=new RequestParams();
        if(map!=null&&map.size()>0){
            for(Map.Entry<String, Object> entry : map.entrySet()){  
                requestParams.put(entry.getKey(), entry.getValue());
            } 
        }
        if(method.equals(ANDROID_ASYNC_HTTP_GET_REQUEST)){
            if(map!=null&&map.size()>0){
                asyncHttpClient.get(path,requestParams,callback);
            }else{
                asyncHttpClient.get(path,callback);
            }
        }else if(method.equals(ANDROID_ASYNC_HTTP_POST_REQUEST)){
            if(map!=null&&map.size()>0){
                asyncHttpClient.post(path,requestParams,callback);
            }else{
                asyncHttpClient.post(path,callback);
            }
        }else if(method.equals(ANDROID_ASYNC_HTTP_PUT_REQUEST)){
            if(map!=null&&map.size()>0){
                asyncHttpClient.put(path,requestParams,callback);
            }else{
                asyncHttpClient.put(path,callback);
            }
        }
    }

}

贴上自己的小例子:

import java.util.Arrays;
import org.xutils.common.util.LogUtil;
import com.example.mytoolutils.MyAppliation;
import com.example.mytoolutils.R;
import com.example.mytoolutils.R.id;
import com.example.mytoolutils.R.layout;
import com.example.mytoolutils.utils.framework.AndroidAsyncHttpUtils;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.BinaryHttpResponseHandler;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

public class AndroidAsyncHttpActivity extends Activity implements OnClickListener {
    private ImageView image;TextView text;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_android_async_http);
        initview();
    }
    private void initview() {
        findViewById(R.id.downloadimage).setOnClickListener(this);
        findViewById(R.id.downloadstring).setOnClickListener(this);
        image=(ImageView) findViewById(R.id.image);
        text=(TextView) findViewById(R.id.text);
    }
    BinaryHttpResponseHandler callback=new BinaryHttpResponseHandler(){
        public void onSuccess(byte[] binaryData) {
            final Bitmap bitmap=BitmapFactory.decodeByteArray(binaryData, 0, binaryData.length-1);
            LogUtil.i("图片下载成功:"+bitmap);
            runOnUiThread(new Runnable() {
                public void run() {
                    image.setImageBitmap(bitmap);
                }
            });
        };
        public void onFailure(int statusCode, org.apache.http.Header[] headers, byte[] binaryData, Throwable error) {
            LogUtil.i("图片下载失败:"+Arrays.toString(binaryData));
        };
    };
    AsyncHttpResponseHandler mcallback=new AsyncHttpResponseHandler(){
        public void onSuccess(int statusCode, String content) {
            LogUtil.i("访问成功:"+content.toString());
            text.setText(content.toString());
        };
        public void onFailure(Throwable error, String content) {
            LogUtil.i("访问失败:"+content.toString()+error);
        };
    };
    AsyncHttpResponseHandler bitmapcallback=new AsyncHttpResponseHandler(){
        public void onSuccess(int arg0, org.apache.http.Header[] arg1, byte[] arg2) {
            Bitmap bitmap=BitmapFactory.decodeByteArray(arg2, 0, arg2.length-1);
            image.setImageBitmap(bitmap);
        };
        public void onFailure(Throwable error, String content) {
            LogUtil.i("bitmapcallback访问失败:"+content.toString()+error);
        };
    };
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.downloadimage:
            AndroidAsyncHttpUtils.getInstance().StartAndroidAsyncHttpRequest
            (AndroidAsyncHttpUtils.ANDROID_ASYNC_HTTP_GET_REQUEST, "http://i.imgur.com/DvpvklR.png",null, bitmapcallback);
            break;
        case R.id.downloadstring:
            AndroidAsyncHttpUtils.getInstance().StartAndroidAsyncHttpRequest
            (AndroidAsyncHttpUtils.ANDROID_ASYNC_HTTP_GET_REQUEST, "http://www.open-open.com/lib/view/open1369637365753.html", null, mcallback);
            break;
        }
    }
    @Override
    protected void onDestroy() {
        AndroidAsyncHttpUtils.getInstance().CancelAndroidAsyncHttpRequest(this, true);
        super.onDestroy();
    }
}

R.layout.activity_android_async_http:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.mytoolutils.activity.AndroidAsyncHttpActivity" >

    <Button
        android:id="@+id/downloadimage"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_margin="10dp"
        android:text="bitmap" />

    <Button
        android:id="@+id/downloadstring"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_margin="10dp"
        android:text="string" />

    <ImageView
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:layout_margin="10dp" />

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_margin="10dp" />

</LinearLayout>
 类似资料: