android-async-http介绍及demo

1.android-async-http简介

基于回调方式的异步http请求框架,基于Apache HttpClient库的,最新版本解决了google
android6.0以上HttpClient不兼容问题.它所有的请求都是位于应用程序主线程UI之外,但任何回调逻辑将在相同的线程上执行回调,使用Android的处理程序创建消息传递
开源项目地址:https://github.com/loopj/android-async-http
特点:
    发送异步HTTP请求,处理响应在匿名回调中完成
    http请求发生在UI线程之外的异步线程中
    内部采用线程池来处理并发请求
    通过RequestParams类构造GET/POST
    内置多文件上传,不需要第三方库支持
    流式json上传,不需要额外第三方库支持
    自动智能请求重试,优化了质量不一的移动连接
    自动解码支持gzip反应速度超快的请求
    二进制文件(图片等)的下载,使用BinaryHttpResponseHandler
    内置响应解析成JSON,使用JsonHttpResponseHandler
    持久化cookie存储,保存cookie到你的应用程序的SharedPreferences

2.官方Demo

下载
# git clone https://github.com/loopj/android-async-http.git
导入as
自动下载:Downloading https://services.gradle.org/distributions/gradle-2.5-all.zip
同步时出现:
Error:Unsupported method: BaseConfig.getApplicationIdSuffix().
The version of Gradle you connect to does not support that method.
To resolve the problem you can change/upgrade the target version of Gradle you connect to.
Alternatively, you can ignore this exception and read other information from the model.
fix:
--- a/build.gradle
+++ b/build.gradle
@@ -4,7 +4,7 @@ buildscript {
     }
 
     dependencies {
-        classpath 'com.android.tools.build:gradle:1.3.1'
+        classpath 'com.android.tools.build:gradle:3.0.1'
     }
 }
 
@@ -14,7 +14,7 @@ def isReleaseBuild() {
 
 allprojects {
     group = 'com.loopj.android'
-    version = '1.5.0-SNAPSHOT'
+    version = '1.8.0-SNAPSHOT'
同步后出现
Error:All flavors must now belong to a named flavor dimension. Learn more at https://d.android.com/r/tools/flavorDimensions-missing-error-message.html
fix:
--- a/library/build.gradle
+++ b/library/build.gradle
@@ -7,6 +7,7 @@ android {
     defaultConfig {
         minSdkVersion 9
         targetSdkVersion 23
+        flavorDimensions "versionCode"
         consumerProguardFiles 'proguard.txt'
     }

--- a/sample/build.gradle
+++ b/sample/build.gradle
@@ -14,6 +14,7 @@ android {
     defaultConfig {
         minSdkVersion 9
         targetSdkVersion 23
+        flavorDimensions "versionCode"
     }

能成功同步

3.android-async-http核心类介绍

1)AsyncHttpClient:核心类,使用HttpClient执行网络请求,提供get,put,post,delete,head等请求方法
只需以url及RequestParams调用相应的方法即可,必须提供ResponseHandlerInterface的实现类,一般为
AsyncHttpResponseHandler的子类,AsyncHttpClient内部有一个线程池,当使用AsyncHttpClient执行
网络请求时,最终都会调用sendRequest方法,在这个方法内部将请求参数封装成AsyncHttpRequest交由内
部的线程池执行
2)SyncHttpClient:继承自AsyncHttpClient,同步执行网络请求,AsyncHttpClient把请求封装成AsyncHttpRequest
后直接调用它的run方法
3)AsyncHttpRequest:继承自Runnabler,被submit至线程池执行网络请求并发送start,success等消息
4)RequestParams:请求参数,可以添加字符串参数,并可添加File,InputStream上传文件
5)AsyncHttpResponseHandler:接收请求结果,一般重写onSuccess及onFailure接收请求成功或失败的消息
还有onStart,onFinish等消息
6)TextHttpResponseHandler:继承自AsyncHttpResponseHandler,将请求结果由byte数组转成了String
7)JsonHttpResponseHandler:继承自TextHttpResponseHandler,将请求结果由String转换成JSONObject
或JSONArray
8)BaseJsonHttpResponseHandler:继承自TextHttpResponseHandler,是一个泛型类,可以直接原始解析


4.使用android-async-http

在Module:app里添加
dependencies {
    compile 'com.loopj.android:android-async-http:1.4.9'
}

json测试数据:
{"people": [{"name":"zhangbing"},{"name": "linbing"},{"name": "lingbing"}]}

public class MainActivity extends AppCompatActivity {
    private Button btGet;
    private Button btPost;
    private Button btDownload;
    private Button btUpLoad;
    private Button btJson;
    private Button btPicture;
    private ImageView iv;

    private TextView tv;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btGet  = (Button)findViewById(R.id.btGet);
        btPost = (Button)findViewById(R.id.btPost);
        btDownload = (Button)findViewById(R.id.btDownload);
        btUpLoad   = (Button)findViewById(R.id.btUpload);
        btJson     = (Button)findViewById(R.id.btJson);
        btPicture  = (Button)findViewById(R.id.btPicture);
        iv = (ImageView)findViewById(R.id.imageView);

        tv = (TextView)findViewById(R.id.textView);

        btGet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

               AsyncHttpClient client= new AsyncHttpClient();
                client.get("https://www.baidu.com", new TextHttpResponseHandler() {


                    @Override
                    public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {

                    }

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, String responseString) {
                        tv.setText(responseString);
                        Log.i("tag",responseString);
                    }
                });
            }
        });

        btPost.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String url = "http://apicloud.mob.com/v1/mobile/address/query";
                AsyncHttpClient http = new AsyncHttpClient();
                RequestParams params = new RequestParams();
                params.add("key","1922d51a5257d");
                params.add("phone","17781046785");

                http.post(url, params, new TextHttpResponseHandler() {
                    @Override
                    public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {

                    }

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, String responseString) {
                        tv.setText(responseString);
                    }
                });
            }
        });

        //下载文件到内置SD卡
        btDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String url = "http://192.168.42.144:8080/CompassDemo.zip";

                //下载之后存放的路径Environment.getExternalStorageDirectory()
                File file = new File(Environment.getExternalStorageDirectory(),url.substring(url.lastIndexOf("/")+1));

                AsyncHttpClient http = new AsyncHttpClient();
                http.get(url, new FileAsyncHttpResponseHandler(file) {

                    @Override
                    public void onStart() {
                        super.onStart();
                        tv.setText("开始下载...");
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, Throwable throwable, File file) {
                        tv.setText("下载失败...");
                    }

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, File file) {
                        if(statusCode == 200){
                            tv.setText("下载文件成功:下载路径:"+file.getPath());
                        }
                    }
                });
            }
        });

        //上传文件
        btUpLoad.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String url="http://192.168.42.144:8080/";
                AsyncHttpClient http = new AsyncHttpClient();
                RequestParams params = new RequestParams();
                File file = new File("/storage/emulated/0/wifi");

                try{
                   params.put("file",file);
                   http.post(url,params, new AsyncHttpResponseHandler() {
                       @Override
                       public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                           if(statusCode==200){
                               tv.setText("上传成功");
                           }
                       }

                       @Override
                       public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                            tv.setText("上传失败");
                       }
                   });
                }catch (FileNotFoundException e){
                    e.printStackTrace();
                }
            }
        });

        btJson.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               String url = "http://192.168.42.144:8080/gson";
               AsyncHttpClient http = new AsyncHttpClient();
               http.get(url, new JsonHttpResponseHandler(){
                   //onSuccess方法里response参数类型应该根据返回值类型设定
                   @Override
                   public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                       super.onSuccess(statusCode, headers, response);
                       if(statusCode == 200){
                           //遍历json数组

                               try{
                                   JSONArray array = response.getJSONArray("people");
                                   StringBuilder stringBuilder = new StringBuilder();
                                   for(int i=0; i< array.length(); i++){
                                       stringBuilder.append(array.getJSONObject(i).getString("name")+"\n");
                                   }
                                   tv.setText(stringBuilder.toString());

                               }catch (JSONException e){
                                   e.printStackTrace();
                               }

                       }
                   }

                   @Override
                   public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                       super.onFailure(statusCode, headers, responseString, throwable);
                       tv.setText("Json下载失败");
                   }
               });

            }
        });

        btPicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String url = "http://192.168.42.144:8080/flower.jpeg";
                AsyncHttpClient client = new AsyncHttpClient();
                client.get(url, new BinaryHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, byte[] binaryData) {
                        Bitmap bmp = BitmapFactory.decodeByteArray(binaryData,0, binaryData.length);
                        iv.setImageBitmap(bmp);
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, byte[] binaryData, Throwable error) {

                    }
                });
            }
        });
    }
}

android-async-http介绍及demo_第1张图片


你可能感兴趣的:(Android框架学习)