使用AsyncHttpClient框架来完成网络数据的请求
2014-09-01 00:46
766 查看
好几天没有到自己的博客里写点文章了,今天在做项目之余花点时间来写一篇文章。由于本人在一个基于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
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.
This library also includes a
that automatically saves cookies to
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
Now set this client’s cookie store to be a new instance of
context (usually
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
See the PersistentCookieStore Javadoc for more information.
The
be built and constructed in various ways:
Create empty
Create
Create
key/value strings:
See the RequestParams Javadoc for more information.
The
Add an
upload:
Add a
upload:
Add a byte array to the
See the RequestParams Javadoc for more information.
The
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
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
installed Android SDK and Gradle buildscript, then just run:
This will generate a file in path
以上大部分的使用都是来自于官方网站的基本用例介绍,简介明了所以直接拿过来了。
接下来是我使用AsyncHttpClient的一个简单的demo的记录和分享:
对我Android端来说从服务器端获取数据是现在Android中必备的或者说是必须的,服务器端写app接口把Android端需要的数据转换为json数据丢给Android端,App端通过HTTP请求去获得服务器端提供的json数据。
如下将是此demo的主要代码:
微信商城系统
对于代码而言看起来应该是比较简单的,但是我们需要注意的是我们需要确保服务器端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
本文中主要使用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
dependencies { compile 'com.loopj.android:android-async-http:1.4.5' }
Import the http package.
import com.loopj.android.http.*;
Create a new
AsyncHttpClientinstance and make a request:
AsyncHttpClient client = new AsyncHttpClient(); client.get("http://www.google.com", new AsyncHttpResponseHandler() { @Override public void onStart() { // called before request is started } @Override public void onSuccess(int statusCode, Header[] headers, byte[] response) { // called when response HTTP status is "200 OK" } @Override public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) { // called when response HTTP status is "4XX" (eg. 401, 403, 404) } @Override public void onRetry(int retryNo) { // called when request is retried } });
Recommended Usage: Make a Static Http Client
In this example, we’ll make a http client class with static accessors to make it easy to communicate with Twitter’s API.import com.loopj.android.http.*;
public class TwitterRestClient {
private static final String BASE_URL = "http://api.twitter.com/1/";
private static AsyncHttpClient client = new AsyncHttpClient();
public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(getAbsoluteUrl(url), params, responseHandler);
}
public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(getAbsoluteUrl(url), params, responseHandler);
}
private static String getAbsoluteUrl(String relativeUrl) {
return BASE_URL + relativeUrl;
}
}
This then makes it very easy to work with the Twitter API in your code:
import org.json.*;
import com.loopj.android.http.*;
class TwitterRestClientUsage {
public void getPublicTimeline() throws JSONException {
TwitterRestClient.get("statuses/public_timeline.json", null, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// If the response is JSONObject instead of expected JSONArray
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
// Pull out the first event on the public timeline
JSONObject firstEvent = timeline.get(0);
String tweetText = firstEvent.getString("text");
// Do something with the response
System.out.println(tweetText);
}
});
}
}
Check out the AsyncHttpClient, RequestParams and AsyncHttpResponseHandlerJavadocs
for more details.
Persistent Cookie Storage with PersistentCookieStore
This library also includes a PersistentCookieStorewhich is an implementation of the Apache HttpClient
CookieStoreinterface
that automatically saves cookies to
SharedPreferencesstorage 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:
AsyncHttpClient myClient = new AsyncHttpClient();
Now set this client’s cookie store to be a new instance of
PersistentCookieStore, constructed with an activity or application
context (usually
thiswill suffice):
PersistentCookieStore myCookieStore = new PersistentCookieStore(this); myClient.setCookieStore(myCookieStore);
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:
BasicClientCookie newCookie = new BasicClientCookie("cookiesare", "awesome"); newCookie.setVersion(1); newCookie.setDomain("mydomain.com"); newCookie.setPath("/"); myCookieStore.addCookie(newCookie);
See the PersistentCookieStore Javadoc for more information.
Adding GET/POST Parameters with RequestParams
The RequestParamsclass is used to add optional GET or POST parameters to your requests.
RequestParamscan
be built and constructed in various ways:
Create empty
RequestParamsand immediately add some parameters:
RequestParams params = new RequestParams(); params.put("key", "value"); params.put("more", "data");
Create
RequestParamsfor a single parameter:
RequestParams params = new RequestParams("single", "value");
Create
RequestParamsfrom an existing
Mapof
key/value strings:
HashMap<String, String> paramMap = new HashMap<String, String>(); paramMap.put("key", "value"); RequestParams params = new RequestParams(paramMap);
See the RequestParams Javadoc for more information.
Uploading Files with RequestParams
The RequestParamsclass additionally supports multipart file uploads as follows:
Add an
InputStreamto the
RequestParamsto
upload:
InputStream myInputStream = blah; RequestParams params = new RequestParams(); params.put("secret_passwords", myInputStream, "passwords.txt");
Add a
Fileobject to the
RequestParamsto
upload:
File myFile = new File("/path/to/file.png"); RequestParams params = new RequestParams(); try { params.put("profile_picture", myFile); } catch(FileNotFoundException e) {}
Add a byte array to the
RequestParamsto upload:
byte[] myByteArray = blah; RequestParams params = new RequestParams(); params.put("soundtrack", new ByteArrayInputStream(myByteArray), "she-wolf.mp3");
See the RequestParams Javadoc for more information.
Downloading Binary Data with FileAsyncHttpResponseHandler
The FileAsyncHttpResponseHandlerclass can be used to fetch binary data such as images and other files. For example:
AsyncHttpClient client = new AsyncHttpClient(); client.get("http://example.com/file.png", new FileAsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, File response) { // Do something with the file `response` } });
See the FileAsyncHttpResponseHandler Javadoc for more information.
Adding HTTP Basic Auth credentials
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.
AsyncHttpClient client = new AsyncHttpClient(); client.setBasicAuth("username","password/token"); client.get("http://example.com");
You can also provide a more specific Authentication Scope (recommended)
AsyncHttpClient client = new AsyncHttpClient(); client.setBasicAuth("username","password", new AuthScope("example.com", 80, AuthScope.ANY_REALM)); client.get("http://example.com");
See the RequestParams Javadoc for more information.
Testing on device
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:
gradle :sample:installDebug
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
Building from Source
To build a .jarfile 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:
gradle :library:jarRelease
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
相关文章推荐
- AsyncHttpClient 网络请求+ fastJson解析数据
- 使用android-async-http来封装Android网络请求框架
- android使用asynchttp网络请求服务器返回json数据并显示在手机
- 【已解决】使用android-async-http网络请求框架出现Header[]不识别错误的解决办法
- AsyncHttpClient请求网络数据小节!
- Android-网络请求数据使用apache httpclient v4
- android(21)(使用HttpURLConnection,HttpClient和AsyncHttpClient分别实现post和get请求数据)
- Android网络请求框架--AsyncHttpClient
- Android 网络请求框架android-async-http简单使用
- Android 使用android-async-http网络请求框架出现Header[]不识别错误的解决办法
- Android网络请求框架:Android-async-http简单使用
- 使用HttpURLConnection和使用HttpClient方式请求网络采用get方式和post方式请求数据
- Android网络请求库android-async-http使用
- Android 网络提交数据(使用Asynchronous Http Client)
- Android 网络提交数据(使用Asynchronous Http Client)
- 无废话Android之内容观察者ContentObserver、获取和保存系统的联系人信息、网络图片查看器、网络html查看器、使用异步框架Android-Async-Http(4)
- 【Android】【嘿!Java】Android工程、Java工程中通过HttpClient请求网络数据的不同方式
- Android之网络----使用HttpClient发送HTTP请求(通过get方法获取数据)
- android上传图片到服务器(使用base64字节流的形式通过 AsyncHttpClient框架传输)
- Android 网络请求框架android-async-http问题