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

来源:互联网 发布:java入门书推荐 编辑:程序博客网 时间:2024/05/11 15:32

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

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

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


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


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

具体使用的类:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
packagecom.http;
 
importjava.io.File;
importjava.io.FileOutputStream;
 
importorg.json.JSONArray;
importorg.json.JSONObject;
 
importandroid.app.Activity;
importandroid.app.ProgressDialog;
importandroid.os.Bundle;
importandroid.os.Environment;
importandroid.util.Log;
importandroid.view.View;
importandroid.widget.TextView;
importandroid.widget.Toast;
 
importcom.loopj.android.http.AsyncHttpResponseHandler;
importcom.loopj.android.http.BinaryHttpResponseHandler;
importcom.loopj.android.http.JsonHttpResponseHandler;
importcom.loopj.android.http.RequestParams;
 
publicclass MainActivity extendsActivity {
    privateTextView textView; // 顶部textview
    privateProgressDialog pDialog;
    privateTextView textView2; // 下面textview,显示获取的所有数据
    @Override
    protectedvoid onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView) findViewById(R.id.text);
        textView2 = (TextView) findViewById(R.id.text2);
    }
    publicvoid method1(View view) {
        pDialog = ProgressDialog.show(this"请稍等""数据加载中");
        String urlString = "http://client.azrj.cn/json/cook/cook_list.jsp?type=1&p=2&size=10"; // 一個獲取菜谱的url地址
        HttpUtil.get(urlString, newAsyncHttpResponseHandler() {
            publicvoid onSuccess(String arg0) { // 获取数据成功会调用这里
                pDialog.dismiss();
                textView.setText("获取json数据成功,看下面");
                textView2.setText(arg0);
                Log.i("hck", arg0);
            };
            publicvoid onFailure(Throwable arg0) { // 失败,调用
                Toast.makeText(MainActivity.this"onFailure",
                        Toast.LENGTH_LONG).show();
            };
            publicvoid onFinish() { // 完成后调用,失败,成功,都要掉
            };
        });
    }
    publicvoid method2(View view) {
        String urlString = "http://client.azrj.cn/json/cook/cook_list.jsp?";
        RequestParams params = newRequestParams(); // 绑定参数
        params.put("type""1");
        params.put("p""2");
        params.put("size""10");
        HttpUtil.get(urlString, params, newJsonHttpResponseHandler() {
            publicvoid onSuccess(JSONArray arg0) { // 成功后返回一个JSONArray数据
                Log.i("hck", arg0.length() + "");
                try{
                    textView.setText("菜谱名字:"
                            + arg0.getJSONObject(2).getString("name")); //返回的是JSONArray, 获取JSONArray数据里面的第2个JSONObject对象,然后获取名字为name的数据值
                catch(Exception e) {
                    Log.e("hck", e.toString());
                }
            };
            publicvoid onFailure(Throwable arg0) {
                Log.e("hck"" onFailure" + arg0.toString());
            };
            publicvoid onFinish() {
                Log.i("hck""onFinish");
            };
            publicvoid onSuccess(JSONObject arg0) {   //返回的是JSONObject,会调用这里
                Log.i("hck""onSuccess ");
                try{
                    textView.setText("菜谱名字:"
                            + arg0.getJSONArray("list").getJSONObject(0)
                                    .getString("name"));
                catch(Exception e) {
                    Log.e("hck", e.toString());
                }
            };
        });
    }
    publicvoid method3(View view) {
        String urlString = "http://client.azrj.cn/json/cook/cook_list.jsp?type=1&p=2&size=10";
        HttpUtil.get(urlString, newJsonHttpResponseHandler() {
            publicvoid onSuccess(JSONObject arg0) {
                try{
                    textView.setText("菜谱名字:"
                            + arg0.getJSONArray("list").getJSONObject(1)
                                    .getString("name"));
                catch(Exception e) {
                    Log.e("hck", e.toString());
                }
            };
        });
    }
    publicvoid method4(View view) {
        String urlString = "http://client.azrj.cn/json/cook/cook_list.jsp?";
        finalRequestParams params = newRequestParams();
        params.put("type""1");
        params.put("p""2");
        params.put("size""10");
        HttpUtil.get(urlString, params, newAsyncHttpResponseHandler() {
            publicvoid onSuccess(String arg0) {
                try{
                    JSONObject jObject = newJSONObject(arg0);
                    textView.setText("菜谱名字:"
                            + jObject.getJSONArray("list").getJSONObject(2)
                                    .getString("name"));
                    Log.i("hck", params.getEntity().toString());
                catch(Exception e) {
                }
            };
        });
    }
    publicvoid method5(View view) {
        String url = "http://f.hiphotos.baidu.com/album/w%3D2048/sign=38c43ff7902397ddd6799f046dbab3b7/9c16fdfaaf51f3dee973bf7495eef01f3b2979d8.jpg";
        HttpUtil.get(url, newBinaryHttpResponseHandler() {
            @Override
            publicvoid onSuccess(byte[] arg0) {
                super.onSuccess(arg0);
                File file = Environment.getExternalStorageDirectory();
                File file2 = newFile(file, "cat");
                file2.mkdir();
                file2 = newFile(file2, "cat.jpg");
                try{
                    FileOutputStream oStream = newFileOutputStream(file2);
                    oStream.write(arg0);
                    oStream.flush();
                    oStream.close();
                    textView.setText("可爱的猫咪已经保存在sdcard里面");
                catch(Exception e) {
                    e.printStackTrace();
                    Log.i("hck", e.toString());
                }
            }
        });
    }
}

布局文件:


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

 

0 0
原创粉丝点击