您的位置:首页 > 理论基础 > 计算机网络

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

dependencies {
compile 'com.loopj.android:android-async-http:1.4.5'
}


Import the http package.

import com.loopj.android.http.*;


Create a new
AsyncHttpClient
instance 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
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
:

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
this
will 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
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:

RequestParams params = new RequestParams();
params.put("key", "value");
params.put("more", "data");


Create
RequestParams
for a single parameter:

RequestParams params = new RequestParams("single", "value");


Create
RequestParams
from an existing
Map
of
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
RequestParams
class additionally supports multipart file uploads as follows:

Add an
InputStream
to the
RequestParams
to
upload:

InputStream myInputStream = blah;
RequestParams params = new RequestParams();
params.put("secret_passwords", myInputStream, "passwords.txt");


Add a
File
object to the
RequestParams
to
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
RequestParams
to 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
FileAsyncHttpResponseHandler
class 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
.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:

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐