android开源框架android-async-http使用案例介绍

本文介绍了如何使用AndroidAsyncHTTP框架轻松获取网络数据或向服务器发送数据,包括基本设置、方法调用及示例代码解析。重点展示了获取JSON数据的方法,并提供了完整的代码实现与操作流程。

android-async-http开源框架可以是我们轻松的获取网络数据或者向服务器发送数据,使用起来也很简单,下面做简单介绍,具体详细使用看官网:https://github.com/loopj/android-async-http

1.新建项目,去官网下载zip包,解压,打开releases文件,把里面最新的jar包,考入项目工程libs目录下,引入包。

2.通过1,就可以使用了,很简单,下面是自己写的demo,用它提供的各种不同方法完成从服务器获取一个json数据:


01package com.http;
02import com.loopj.android.http.AsyncHttpClient;
03import com.loopj.android.http.AsyncHttpResponseHandler;
04import com.loopj.android.http.BinaryHttpResponseHandler;
05import com.loopj.android.http.JsonHttpResponseHandler;
06import com.loopj.android.http.RequestParams;
07 
08public class HttpUtil {
09    privatestatic     AsyncHttpClient client =newAsyncHttpClient();    //实例话对象
10    static
11    {
12        client.setTimeout(11000);  //设置链接超时,如果不设置,默认为10s
13    }
14    publicstatic void get(String urlString,AsyncHttpResponseHandler res)    //用一个完整url获取一个string对象
15    {
16        client.get(urlString, res);
17    }
18    publicstatic void get(String urlString,RequestParams params,AsyncHttpResponseHandler res)   //url里面带参数
19    {
20        client.get(urlString, params,res);
21    }
22    publicstatic void get(String urlString,JsonHttpResponseHandler res)   //不带参数,获取json对象或者数组
23    {
24        client.get(urlString, res);
25    }
26    publicstatic void get(String urlString,RequestParams params,JsonHttpResponseHandler res)   //带参数,获取json对象或者数组
27    {
28        client.get(urlString, params,res);
29    }
30    publicstatic void get(String uString, BinaryHttpResponseHandler bHandler)   //下载数据使用,会返回byte数据
31    {
32        client.get(uString, bHandler);
33    }
34    publicstatic AsyncHttpClient getClient()
35    {
36        returnclient;
37    }
38}


这个类主要列出了我们常用的get方法,在要使用的地方,调用该类就行了。

具体使用的类:

001package com.http;
002 
003import java.io.File;
004import java.io.FileOutputStream;
005 
006import org.json.JSONArray;
007import org.json.JSONObject;
008 
009import android.app.Activity;
010import android.app.ProgressDialog;
011import android.os.Bundle;
012import android.os.Environment;
013import android.util.Log;
014import android.view.View;
015import android.widget.TextView;
016import android.widget.Toast;
017 
018import com.loopj.android.http.AsyncHttpResponseHandler;
019import com.loopj.android.http.BinaryHttpResponseHandler;
020import com.loopj.android.http.JsonHttpResponseHandler;
021import com.loopj.android.http.RequestParams;
022 
023public class MainActivity extendsActivity {
024    privateTextView textView; // 顶部textview
025    privateProgressDialog pDialog;
026    privateTextView textView2; // 下面textview,显示获取的所有数据
027    @Override
028    protectedvoid onCreate(Bundle savedInstanceState) {
029        super.onCreate(savedInstanceState);
030        setContentView(R.layout.activity_main);
031        textView = (TextView) findViewById(R.id.text);
032        textView2 = (TextView) findViewById(R.id.text2);
033    }
034    publicvoid method1(View view) {
035        pDialog = ProgressDialog.show(this,"请稍等", "数据加载中");
036        String urlString ="http://client.azrj.cn/json/cook/cook_list.jsp?type=1&p=2&size=10"; // 一個獲取菜谱的url地址
037        HttpUtil.get(urlString,new AsyncHttpResponseHandler() {
038            publicvoid onSuccess(String arg0) {// 获取数据成功会调用这里
039                pDialog.dismiss();
040                textView.setText("获取json数据成功,看下面");
041                textView2.setText(arg0);
042                Log.i("hck", arg0);
043            };
044            publicvoid onFailure(Throwable arg0) {// 失败,调用
045                Toast.makeText(MainActivity.this,"onFailure",
046                        Toast.LENGTH_LONG).show();
047            };
048            publicvoid onFinish() { // 完成后调用,失败,成功,都要掉
049            };
050        });
051    }
052    publicvoid method2(View view) {
053        String urlString ="http://client.azrj.cn/json/cook/cook_list.jsp?";
054        RequestParams params =new RequestParams();// 绑定参数
055        params.put("type","1");
056        params.put("p","2");
057        params.put("size","10");
058        HttpUtil.get(urlString, params,new JsonHttpResponseHandler() {
059            publicvoid onSuccess(JSONArray arg0) {// 成功后返回一个JSONArray数据
060                Log.i("hck", arg0.length() +"");
061                try{
062                    textView.setText("菜谱名字:"
063                            + arg0.getJSONObject(2).getString("name"));//返回的是JSONArray, 获取JSONArray数据里面的第2个JSONObject对象,然后获取名字为name的数据值
064                }catch (Exception e) {
065                    Log.e("hck", e.toString());
066                }
067            };
068            publicvoid onFailure(Throwable arg0) {
069                Log.e("hck"," onFailure" + arg0.toString());
070            };
071            publicvoid onFinish() {
072                Log.i("hck","onFinish");
073            };
074            publicvoid onSuccess(JSONObject arg0) {  //返回的是JSONObject,会调用这里
075                Log.i("hck","onSuccess ");
076                try{
077                    textView.setText("菜谱名字:"
078                            + arg0.getJSONArray("list").getJSONObject(0)
079                                    .getString("name"));
080                }catch (Exception e) {
081                    Log.e("hck", e.toString());
082                }
083            };
084        });
085    }
086    publicvoid method3(View view) {
087        String urlString ="http://client.azrj.cn/json/cook/cook_list.jsp?type=1&p=2&size=10";
088        HttpUtil.get(urlString,new JsonHttpResponseHandler() {
089            publicvoid onSuccess(JSONObject arg0) {
090                try{
091                    textView.setText("菜谱名字:"
092                            + arg0.getJSONArray("list").getJSONObject(1)
093                                    .getString("name"));
094                }catch (Exception e) {
095                    Log.e("hck", e.toString());
096                }
097            };
098        });
099    }
100    publicvoid method4(View view) {
101        String urlString ="http://client.azrj.cn/json/cook/cook_list.jsp?";
102        finalRequestParams params = newRequestParams();
103        params.put("type","1");
104        params.put("p","2");
105        params.put("size","10");
106        HttpUtil.get(urlString, params,new AsyncHttpResponseHandler() {
107            publicvoid onSuccess(String arg0) {
108                try{
109                    JSONObject jObject =new JSONObject(arg0);
110                    textView.setText("菜谱名字:"
111                            + jObject.getJSONArray("list").getJSONObject(2)
112                                    .getString("name"));
113                    Log.i("hck", params.getEntity().toString());
114                }catch (Exception e) {
115                }
116            };
117        });
118    }
119    publicvoid method5(View view) {
120        String url ="http://f.hiphotos.baidu.com/album/w%3D2048/sign=38c43ff7902397ddd6799f046dbab3b7/9c16fdfaaf51f3dee973bf7495eef01f3b2979d8.jpg";
121        HttpUtil.get(url,new BinaryHttpResponseHandler() {
122            @Override
123            publicvoid onSuccess(byte[] arg0) {
124                super.onSuccess(arg0);
125                File file = Environment.getExternalStorageDirectory();
126                File file2 =new File(file, "cat");
127                file2.mkdir();
128                file2 =new File(file2,"cat.jpg");
129                try{
130                    FileOutputStream oStream =new FileOutputStream(file2);
131                    oStream.write(arg0);
132                    oStream.flush();
133                    oStream.close();
134                    textView.setText("可爱的猫咪已经保存在sdcard里面");
135                }catch (Exception e) {
136                    e.printStackTrace();
137                    Log.i("hck", e.toString());
138                }
139            }
140        });
141    }
142}

布局文件:


01<ScrollView
02    xmlns:android="http://schemas.android.com/apk/res/android"
03    xmlns:tools="http://schemas.android.com/tools"
04    android:layout_width="match_parent"
05    android:layout_height="match_parent"
06    android:orientation="vertical"
07      android:gravity="center_horizontal"
08    >
09    <LinearLayout
10    android:layout_width="fill_parent"
11    android:layout_height="fill_parent"
12    android:orientation="vertical"
13      android:gravity="center_horizontal">
14    <TextView
15        android:textColor="#FF0000"
16        android:textSize="16sp"
17       android:layout_marginTop="20dp"
18     android:gravity="center_horizontal"
19        android:id="@+id/text"
20        android:layout_width="wrap_content"
21        android:layout_height="wrap_content"
22        android:text="获取数据完成后会显示在这里"/>
23<Button
24    android:layout_marginTop="50dp"
25    android:id="@+id/bt1"
26    android:layout_width="wrap_content"
27    android:layout_height="wrap_content"
28    android:text="第一种"
29    android:onClick="method1"
30    />
31<Button
32    android:id="@+id/bt2"
33    android:layout_width="wrap_content"
34    android:layout_height="wrap_content"
35    android:text="第2种"
36    android:onClick="method2"
37    />
38<Button
39    android:id="@+id/bt3"
40    android:layout_width="wrap_content"
41    android:layout_height="wrap_content"
42    android:text="第3种"
43      android:onClick="method3"
44    />
45<Button
46    android:id="@+id/bt4"
47    android:layout_width="wrap_content"
48    android:layout_height="wrap_content"
49    android:text="第4种"
50      android:onClick="method4"
51    />
52<Button
53    android:id="@+id/bt5"
54    android:layout_width="wrap_content"
55    android:layout_height="wrap_content"
56    android:text="第5种"
57      android:onClick="method5"
58    />
59  <TextView
60        android:textColor="#FF0000"
61        android:textSize="16sp"
62       android:layout_marginTop="20dp"
63     android:gravity="center_horizontal"
64        android:id="@+id/text2"
65        android:layout_width="wrap_content"
66        android:layout_height="wrap_content"
67         />
68</LinearLayout>
69</ScrollView>

很简单很实用,上面只是get方法的,上传数据,和这个也差不多,大家自己建个服务器,试试。记得加入网文网络的权限和向sdcard的访问权限

Asynchronous Http Client for Android Build Status An asynchronous, callback-based Http client for Android built on top of Apache's HttpClient libraries. Changelog See what is new in version 1.4.9 released on 19th September 2015 https://github.com/loopj/android-async-http/blob/1.4.9/CHANGELOG.md Javadoc Latest Javadoc for 1.4.9 release are available here (also included in Maven repository): https://loopj.com/android-async-http/doc/ Features Make asynchronous HTTP requests, handle responses in anonymous callbacks HTTP requests happen outside the UI thread Requests use a threadpool to cap concurrent resource usage GET/POST params builder (RequestParams) Multipart file uploads with no additional third party libraries Tiny size overhead to your application, only 60kb for everything Automatic smart request retries optimized for spotty mobile connections Automatic gzip response decoding support for super-fast requests Optional built-in response parsing into JSON (JsonHttpResponseHandler) Optional persistent cookie store, saves cookies into your app's SharedPreferences Examples For inspiration and testing on device we've provided Sample Application. See individual samples here on Github To run Sample application, simply clone the repository and run this command, to install it on connected device gradle :sample:installDebug Maven You can now integrate this library in your project via Maven. There are available two kind of builds. releases, maven central https://repo1.maven.org/maven2/com/loopj/android/android-async-http/ Maven URL: https://repo1.maven.org/maven2/ GroupId: com.loopj.android ArtifactId: android-async-http Version: 1.4.9 Packaging: JAR or AAR Gradle repositories { maven { mavenCentral() } } dependencies { compile 'com.loopj.android:android-async-http:1.4.9' } development snapshots https://oss.sonatype.org/content/repositories/snapshots/com/loopj/android/android-async-http/ Maven URL: https://oss.sonatype.org/content/repositories/snapshots/ GroupId: com.loopj.android ArtifactId: android-async-http Version: 1.5.0-SNAPSHOT Packaging: JAR or AAR Gradle repositories { maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' } } dependencies { compile 'com.loopj.android:android-async-http:1.5.0-SNAPSHOT' } Documentation, Features and Examples Full details and documentation can be found on the project page here: https://loopj.com/android-async-http/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值