好几天没有到自己的博客里写点文章了,今天在做项目之余花点时间来写一篇文章。由于本人在一个基于Android的购物平台,目前pc端基本功能都已经写好,Android的基本UI界面都已经OK,pc端接口也已有序的完成,现在只有Android客户端通过HTPP请求获取pc端数据没有写了,周末之余花点时间来写写。要进行网络请求就想到找找比较优秀的网络请求框架使用来提高自己的技术,也许这个可能和大多数人一样不断的追寻新的东西才能有所成长,我也不例外,也时常的追寻一些新的东西融入到项目中去。找了找看到网络上有很多这样的框架有功能比较全面的框架如:Xutils框架,afinal框架,ThinkAndroid等,也有针对网络请求的volley和AsyncHttpClient框架。
本文中主要使用AsyncHttpClient框架来写。我要说的是AsyncHttpClient框架确实挺不错的,看着这样的代码就很舒服,使用也很方便。
1.首先我们需要去下载AsyncHttpClient框架:
如果不知道在哪里下载请猛戳这里:Android开发AsyncHttpClient框架 这个是下载网址这里有很好的demo可以供我们学习之用。
也可以直接到github中进行下载如果需要到github中下载请猛戳这里:Android开发AsyncHttpClient框架
2.安装和基本的使用
(首先我要备注和声明下 我用的开发工具是 AndroidStudio version:0.8.8)
Add maven dependency using Gradle buildscript in format
Import the http package.
Create a new AsyncHttpClient
instance and make a request:
In this example, we’ll make a http client class with static accessors to make it easy to communicate with Twitter’s API.
This then makes it very easy to work with the Twitter API in your code:
Check out the AsyncHttpClient, RequestParams and AsyncHttpResponseHandlerJavadocs for more details.
PersistentCookieStore
This library also includes a PersistentCookieStore
which is an implementation of the Apache HttpClient CookieStore
interface that automatically saves cookies to SharedPreferences
storage on the Android device.
This is extremely useful if you want to use cookies to manage authentication sessions, since the user will remain logged in even after closing and re-opening your app.
First, create an instance of AsyncHttpClient
:
Now set this client’s cookie store to be a new instance of PersistentCookieStore
, constructed with an activity or application context (usually this
will suffice):
Any cookies received from servers will now be stored in the persistent cookie store.
To add your own cookies to the store, simply construct a new cookie and call addCookie
:
See the PersistentCookieStore Javadoc for more information.
RequestParams
The RequestParams
class is used to add optional GET or POST parameters to your requests.RequestParams
can be built and constructed in various ways:
Create empty RequestParams
and immediately add some parameters:
Create RequestParams
for a single parameter:
Create RequestParams
from an existing Map
of key/value strings:
See the RequestParams Javadoc for more information.
RequestParams
The RequestParams
class additionally supports multipart file uploads as follows:
Add an InputStream
to the RequestParams
to upload:
Add a File
object to the RequestParams
to upload:
Add a byte array to the RequestParams
to upload:
See the RequestParams Javadoc for more information.
FileAsyncHttpResponseHandler
The FileAsyncHttpResponseHandler
class can be used to fetch binary data such as images and other files. For example:
See the FileAsyncHttpResponseHandler Javadoc for more information.
Some requests may need username/password credentials when dealing with API services that use HTTP Basic Access Authentication requests. You can use the method setBasicAuth()
to provide your credentials.
Set username/password for any host and realm for a particular request. By default the Authentication Scope is for any host, port and realm.
You can also provide a more specific Authentication Scope (recommended)
See the RequestParams Javadoc for more information.
You can test the library on real device or emulator using provided Sample Application. Sample application implements all important functions of library, you can use it as source of inspiration.
Source code of sample application: https://github.com/loopj/android-async-http/tree/master/sample
To run sample application, clone the android-async-http github repository and run command in it’s root:
Which will install Sample application on connected device, all examples do work immediately, if not please file bug report on https://github.com/loopj/android-async-http/issues
To build a .jar
file from source, first make a clone of the android-async-http github repository. Then you have to have installed Android SDK and Gradle buildscript, then just run:
This will generate a file in path {repository_root}/library/build/libs/library-1.4.5.jar
.
以上大部分的使用都是来自于官方网站的基本用例介绍,简介明了所以直接拿过来了。
接下来是我使用AsyncHttpClient的一个简单的demo的记录和分享:
对我Android端来说从服务器端获取数据是现在Android中必备的或者说是必须的,服务器端写app接口把Android端需要的数据转换为json数据丢给Android端,App端通过HTTP请求去获得服务器端提供的json数据。
如下将是此demo的主要代码:
//判断是否有网络
if (!Util.checkNetWorkStatus(MyActivity.this)){
Toast.makeText(MyActivity.this, "没有连接网络!", Toast.LENGTH_SHORT).show();
return;
}else{
AsyncHttpClient client = new AsyncHttpClient();
String url = "http://www.yiicms.net/app/?route=app&list=home";
client.get(url,new JsonHttpResponseHandler(){
//返回JSONObject对象|JSONOArray对象
@Override
public void onSuccess(int statusCode, Header[] headers,
JSONObject response) {
// TODO Auto-generated method stub
super.onSuccess(statusCode, headers, response);
if (statusCode == 200) {
try {
JSONArray array = response.getJSONArray("data");
for (int i = 0;i < array.length(); i++){
JSONObject object = array.getJSONObject(i);
System.out.println("价格"+object.getString("price"));
Util.alertMsg(MyActivity.this,"价格"+object.getString("price"));
}
// Util.alertMsg(MyActivity.this,array+"");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
}
对于代码而言看起来应该是比较简单的,但是我们需要注意的是我们需要确保服务器端json数据返回JSONObject对象|JSONOArray对象,这一点很重要
因为只有确定了这一点我们才能保证client.get(url,new JsonHttpResponseHandler(){});此处我们的请求能够成功。那么如何判断我们这里
public void onSuccess(int statusCode, Header[] headers, JSONObject response)该用JSONObject对象|JSONOArray对象呢?
android中json的浅薄理解
JSONObject 表示形式 {"key" : "value"}
JSONArray 表示形式 [{"key" : "value"},{"key" : "value"},{"key" : "value"}],JSONArray里面包含多个JSONObject
访问时通过 JSONObject对象去访问,使用 jsonObject.getXXX("key")得到相应的值
一般解析JSON都使用这两个。
这里我写的接口中提交过来的数据格式如下所示{"data": [{"key" : "value"},{"key" : "value"},{"key" : "value"}]}
这里我们可以判断我们在请求的时候即public void onSuccess(int statusCode, Header[] headers, JSONObject response)这里的参数我们应该用JSONObject对象,本人就是最初的时候没有打印接口的json数据错误的选择了JSONArray而导致网络请求无果而进行了漫长的无用功。所以这里请大家打印一下自己写的接口或者提供的接口的数据
public void onSuccess(int statusCode, Header[] headers,
JSONObject response) {
Util.alertMsg(MyActivity.this,response+"");
}
有此我们就可以来判断我们选择哪种json数据类型。
(备注)Util.alertMsg()打印数据 是我把一下常用的东西写到了一个工具类中使用,大家可以直接使用
此方式Toast.makeText(MyActivity.this, response+"", Toast.LENGTH_SHORT).show();
写到这里本人的最大感慨就是:时间是把杀猪刀啊!好久不写这些东西越来越生疏了!以后得多花点时间写写了,免得被时间给kill了!
作者:http://www.yiicms.net