原文地址: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数据:

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
package com.http;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.BinaryHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
 
public class HttpUtil {
    private static     AsyncHttpClient client =new AsyncHttpClient();    //实例话对象
    static
    {
        client.setTimeout(11000);   //设置链接超时,如果不设置,默认为10s
    }
    public static void get(String urlString,AsyncHttpResponseHandler res)    //用一个完整url获取一个string对象
    {
        client.get(urlString, res);
    }
    public static void get(String urlString,RequestParams params,AsyncHttpResponseHandler res)   //url里面带参数
    {
        client.get(urlString, params,res);
    }
    public static void get(String urlString,JsonHttpResponseHandler res)   //不带参数,获取json对象或者数组
    {
        client.get(urlString, res);
    }
    public static void get(String urlString,RequestParams params,JsonHttpResponseHandler res)   //带参数,获取json对象或者数组
    {
        client.get(urlString, params,res);
    }
    public static void get(String uString, BinaryHttpResponseHandler bHandler)   //下载数据使用,会返回byte数据
    {
        client.get(uString, bHandler);
    }
    public static AsyncHttpClient getClient()
    {
        return client;
    }
}

这个类主要列出了我们常用的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
package com.http;
 
import java.io.File;
import java.io.FileOutputStream;
 
import org.json.JSONArray;
import org.json.JSONObject;
 
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
 
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.BinaryHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
 
public class MainActivity extends Activity {
    private TextView textView; // 顶部textview
    private ProgressDialog pDialog;
    private TextView textView2; // 下面textview,显示获取的所有数据
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView) findViewById(R.id.text);
        textView2 = (TextView) findViewById(R.id.text2);
    }
    public void 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, new AsyncHttpResponseHandler() {
            public void onSuccess(String arg0) { // 获取数据成功会调用这里
                pDialog.dismiss();
                textView.setText("获取json数据成功,看下面");
                textView2.setText(arg0);
                Log.i("hck", arg0);
            };
            public void onFailure(Throwable arg0) { // 失败,调用
                Toast.makeText(MainActivity.this, "onFailure",
                        Toast.LENGTH_LONG).show();
            };
            public void onFinish() { // 完成后调用,失败,成功,都要掉
            };
        });
    }
    public void method2(View view) {
        String urlString = "http://client.azrj.cn/json/cook/cook_list.jsp?";
        RequestParams params = new RequestParams(); // 绑定参数
        params.put("type", "1");
        params.put("p", "2");
        params.put("size", "10");
        HttpUtil.get(urlString, params, new JsonHttpResponseHandler() {
            public void 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());
                }
            };
            public void onFailure(Throwable arg0) {
                Log.e("hck", " onFailure" + arg0.toString());
            };
            public void onFinish() {
                Log.i("hck", "onFinish");
            };
            public void 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());
                }
            };
        });
    }
    public void method3(View view) {
        String urlString = "http://client.azrj.cn/json/cook/cook_list.jsp?type=1&p=2&size=10";
        HttpUtil.get(urlString, new JsonHttpResponseHandler() {
            public void onSuccess(JSONObject arg0) {
                try {
                    textView.setText("菜谱名字:"
                            + arg0.getJSONArray("list").getJSONObject(1)
                                    .getString("name"));
                } catch (Exception e) {
                    Log.e("hck", e.toString());
                }
            };
        });
    }
    public void method4(View view) {
        String urlString = "http://client.azrj.cn/json/cook/cook_list.jsp?";
        final RequestParams params = new RequestParams();
        params.put("type", "1");
        params.put("p", "2");
        params.put("size", "10");
        HttpUtil.get(urlString, params, new AsyncHttpResponseHandler() {
            public void onSuccess(String arg0) {
                try {
                    JSONObject jObject = new JSONObject(arg0);
                    textView.setText("菜谱名字:"
                            + jObject.getJSONArray("list").getJSONObject(2)
                                    .getString("name"));
                    Log.i("hck", params.getEntity().toString());
                } catch (Exception e) {
                }
            };
        });
    }
    public void method5(View view) {
        String url = "http://f.hiphotos.baidu.com/album/w%3D2048/sign=38c43ff7902397ddd6799f046dbab3b7/9c16fdfaaf51f3dee973bf7495eef01f3b2979d8.jpg";
        HttpUtil.get(url, new BinaryHttpResponseHandler() {
            @Override
            public void onSuccess(byte[] arg0) {
                super.onSuccess(arg0);
                File file = Environment.getExternalStorageDirectory();
                File file2 = new File(file, "cat");
                file2.mkdir();
                file2 = new File(file2, "cat.jpg");
                try {
                    FileOutputStream oStream = new FileOutputStream(file2);
                    oStream.write(arg0);
                    oStream.flush();
                    oStream.close();
                    textView.setText("可爱的猫咪已经保存在sdcard里面");
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i("hck", e.toString());
                }
            }
        });
    }
}

布局文件:

<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>

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

android开源框架android-async-http使用的更多相关文章

  1. Android 开源框架Universal-Image-Loader学习

    Android 开源框架Universal-Image-Loader完全解析(一)--- 基本介绍及使用 Android 开源框架Universal-Image-Loader完全解析(二)--- 图片 ...

  2. Android 开源框架Universal-Image-Loader完全解析(三)---源代码解读

    转载请注明本文出自xiaanming的博客(http://blog.csdn.net/xiaanming/article/details/39057201),请尊重他人的辛勤劳动成果,谢谢! 本篇文章 ...

  3. Android 开源框架Universal-Image-Loader完全解析(二)--- 图片缓存策略详解

    转载请注明本文出自xiaanming的博客(http://blog.csdn.net/xiaanming/article/details/26810303),请尊重他人的辛勤劳动成果,谢谢! 本篇文章 ...

  4. Android进阶笔记13:RoboBinding(实现了数据绑定 Presentation Model(MVVM) 模式的Android开源框架)

    1.RoboBinding RoboBinding是一个实现了数据绑定 Presentation Model(MVVM) 模式的Android开源框架.从简单的角度看,他移除了如addXXListen ...

  5. android 开源框架推荐

    同事整理的 android 开源框架,个个都堪称经典.32 个赞! 1.volley 项目地址 https://github.com/smanikandan14/Volley-demo (1)  JS ...

  6. Android 开源框架Universal-Image-Loader全然解析(二)--- 图片缓存策略具体解释

    转载请注明本文出自xiaanming的博客(http://blog.csdn.net/xiaanming/article/details/26810303),请尊重他人的辛勤劳动成果,谢谢! 本篇文章 ...

  7. Android开源框架Afinal第一篇——揭开圣女的面纱

    Android开源框架Afinal第一篇——揭开圣女的面纱 分类: Android开源框架哪点事2013-09-02 14:25 260人阅读 评论(0) 收藏 举报 Afinal 这是Afinal在 ...

  8. 六款值得推荐的Android开源框架简介

    技术不再多,知道一些常用的.不错的就够了.下面就是最近整理的“性价比”比较高的Android开源框架,应该是相对实用的. 1.volley 项目地址 https://github.com/smanik ...

  9. Android——开源框架Universal-Image-Loader + Fragment使用+轮播广告

    原文地址: Android 开源框架Universal-Image-Loader完全解析(一)--- 基本介绍及使用 Android 开源框架Universal-Image-Loader完全解析(二) ...

  10. [转]Android开源框架ImageLoader的完美例子

    Android开源框架ImageLoader的完美例子 2013年8月19日开源框架之Universal_Image_Loader学习 很多人都在讨论如何让图片能在异步加载更加流畅,可以显示大量图片, ...

随机推荐

  1. 转 C# DataTable 和List之间相互转换的方法

    一.List/IEnumerable转换到DataTable/DataView 方法一: /// <summary> /// Convert a List{T} to a DataTabl ...

  2. 网页闯关游戏(riddle webgame)--游戏玩法和整体介绍

    前言: 记得上大学那会, 有位传说中的大牛, 写了一个网页闯关类的游戏. 当时我们玩得不亦乐乎, 也是第一次接触到这种形式的游戏. 不过当时纯玩家心态, 并没有想过去创造一个. 最近想起这事, 突然想 ...

  3. TCP状态变迁流程

    主动建立TCP链接情况: 被动建立TCP链接情况 主动断开链接的情况 被动断开连接的情况 在TIME_WAIT阶段需要停留2倍的MSL,MSL即Maximum Segment Lifetime,表示任 ...

  4. Couldn't open file on client side, trying server side 错误解决

    09-09 09:43:21.651: D/MediaPlayer(3340): Couldn't open file on client side, trying server side09-09 ...

  5. php和js一起实现倒计时功能

    里获取的php服务端的时间 纯JS是获取客服端时间! <?php //php的时间是以秒算.js的时间以毫秒算 date_default_timezone_set('PRC'); //date_ ...

  6. [solr] - defType - 查询权重排序

    Solr的defType有dismax/edismax两种,这两种的区别,可参见:http://blog.csdn.net/duck_genuine/article/details/8060026 下 ...

  7. Spring 中的default-lazy-init="true" 和 lazy-init="true"

    1.spring的default-lazy-init参数 spring在启动的时候,会默认加载会默认加载整个对象实例图,从初始化ACTION配置.到 service配置到dao配置.乃至到数据库连接. ...

  8. mysql数据库优化小结

    一.常见数据库的优化操作 1.表的设计要符合三范式. 2.添加适当的索引,索引对查询速度影响很大,必须添加索引.主键索引,唯一索引,普通索引,全文索引 3.添加适当存储过程,触发器,事务等. 4.读写 ...

  9. OFBIZ:启动之ContainerLoader

    ContainerLoader类实现StartupLoader接口,目的是装入各种Container容器. /** * An OFBiz container. A container can be t ...

  10. sql server中的 SET NOCOUNT ON 的含义

    每次我们在使用查询分析器调试SQL语句的时候,通常会看到一些信息,提醒我们当前有多少个行受到了影响,这是些什么信息?在我们调用的时候这些信息有用吗?是否可以关闭呢? 答案是这些信息在我们的客户端的应用 ...