android开源框架android-async-http使用

android开源框架android-async-http使用

转:http://www.open-open.com/lib/view/open1369637365753.html

       

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

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

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


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


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

具体使用的类:

001 package com.http;
002  
003 import java.io.File;
004 import java.io.FileOutputStream;
005  
006 import org.json.JSONArray;
007 import org.json.JSONObject;
008  
009 import android.app.Activity;
010 import android.app.ProgressDialog;
011 import android.os.Bundle;
012 import android.os.Environment;
013 import android.util.Log;
014 import android.view.View;
015 import android.widget.TextView;
016 import android.widget.Toast;
017  
018 import com.loopj.android.http.AsyncHttpResponseHandler;
019 import com.loopj.android.http.BinaryHttpResponseHandler;
020 import com.loopj.android.http.JsonHttpResponseHandler;
021 import com.loopj.android.http.RequestParams;
022  
023 public class MainActivity extends Activity {
024     private TextView textView; // 顶部textview
025     private ProgressDialog pDialog;
026     private TextView textView2; // 下面textview,显示获取的所有数据
027     @Override
028     protected void 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     public void 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             public void onSuccess(String arg0) { // 获取数据成功会调用这里
039                 pDialog.dismiss();
040                 textView.setText("获取json数据成功,看下面");
041                 textView2.setText(arg0);
042                 Log.i("hck", arg0);
043             };
044             public void onFailure(Throwable arg0) { // 失败,调用
045                 Toast.makeText(MainActivity.this, "onFailure",
046                         Toast.LENGTH_LONG).show();
047             };
048             public void onFinish() { // 完成后调用,失败,成功,都要掉
049             };
050         });
051     }
052     public void 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             public void 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             public void onFailure(Throwable arg0) {
069                 Log.e("hck", " onFailure" + arg0.toString());
070             };
071             public void onFinish() {
072                 Log.i("hck", "onFinish");
073             };
074             public void 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     public void 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             public void 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     public void method4(View view) {
101         String urlString = "http://client.azrj.cn/json/cook/cook_list.jsp?";
102         final RequestParams params = new RequestParams();
103         params.put("type", "1");
104         params.put("p", "2");
105         params.put("size", "10");
106         HttpUtil.get(urlString, params, new AsyncHttpResponseHandler() {
107             public void 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     public void 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             public void 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的访问权限

posted @ 2014-08-12 17:47  新感觉  阅读(383)  评论(0编辑  收藏  举报