androidandroid ndk 网络编程程为什么没有运行到onsuccess

Android网络通信之android-async-http入门 - 博客频道 - CSDN.NET
分类:Android
android-async-http入门
***Android Asynchronous Http Client
A Callback-Based Http Client Library for Android***
所有的requested请求都在UI线程之外发起
进行http异步请求时,处理请求响应都在匿名回调函数中
请求使用一个线程池来限制并发资源使用情况
get/post参数构建器 (RequestParams)
多文件上传,没有额外的第三方库
json流上传,没有额外的第三方库
在你的应用里只要很小的开销,所有的文件只要90kb
自动对超快请求进行gzip响应解码
自动智能的重试优化请求方便质量不一的手机连接
使用FileAsyncHttpResponseHandler把响应直接保存到文件
持久化cookie存储,保存cookie到你的应用程序的SharedPreferences
集成Jackson JSON,Gson或其他JSON(反)序列化库在BaseJsonHttpResponseHandler中
SaxAsyncHttpResponseHandler支持SAX解析器
支持语言和内容编码,而不仅仅是utf - 8
在此网站下都是使用AAH库开发的应用,翻墙进去逛逛吧:
安装和基本用法
在里下载android-async-http-1.4.6.jar(最新版)并导入到工程中。
import Http包
import com.loopj.android.http.*
创建一个新的AsyncHttpClient实例和请求:
AsyncHttpClient client = new AsyncHttpClient();
client.get("", new AsyncHttpResponseHandler() {
public void onStart() {
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
public void onRetry(int retryNo) {
建议用法:静态的Http客户端
在本例中,我们做一个http客户端静态类访问器使它容易与Twitter的API相链接:
import com.loopj.android.http.*;
public class TwitterRestClient {
private static final String BASE_URL = "/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 + relativeU
这样之后很容易在你的代码中使用Twitter API:
import org.json.*;
import com.loopj.android.http.*;
class TwitterRestClientUsage {
public void getPublicTimeline() throws JSONException {
TwitterRestClient.get("statuses/public_timeline.json", null, new JsonHttpResponseHandler() {
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
JSONObject firstEvent = timeline.get(0);
String tweetText = firstEvent.getString("text");
System.out.println(tweetText);
查看,, Javadocs的更多的细节
持久化Cookie存储PersistentCookieStore
这个库还包含一个实现Apache HttpClient CookieStore接口的PersistentCookieStore,自动在Android设备上使用SharedPreferences存储保存cookie。
如果你想使用cookie来管理身份验证会话这是非常有用的,,因为用户将继续登录即使关闭并重启应用程序。
首先,创建一个实例AsyncHttpClient:
AsyncHttpClient myClient = new AsyncHttpClient();
现在将这个客户的cookie存储为PersistentCookieStore的一个新实例,构造一个活动或应用程序上下文(通常这就足够了):
PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
myClient.setCookieStore(myCookieStore);
任何从服务器收到的cookies都会被存储在持久化cookie存储。
添加自己的cookies进行存储,只需构建一个新的cookie和调用addCookie:
BasicClientCookie newCookie = new BasicClientCookie("cookiesare", "awesome")
newCookie.setVersion(1)
newCookie.setDomain("")
newCookie.setPath("/")
myCookieStore.addCookie(newCookie)
添加GET / POST参数RequestParams
RequestParams类是用于添加可选的GET或POST请求参数。RequestParams可以以各种方式建造而成:
建立空RequestParams并立即添加一些参数:
RequestParams params = new RequestParams();
params.put("key", "value");
params.put("more", "data");
创建一个参数的RequestParams:
RequestParams params = new RequestParams("single", "value");
创建一个存在map键值对的字符串RequestParams:
HashMap&String, String& paramMap = new HashMap&String, String&();
paramMap.put("key", "value");
RequestParams params = new RequestParams(paramMap);
查看以获取更多信息。
加参数RequestParams的文件上传
另外RequestParams类支持多部分文件上传,如下所示:
添加一个带有inputStream的requestParams参数用来上传:
InputStream myInputStream =
RequestParams params = new RequestParams();
params.put("secret_passwords", myInputStream, "passwords.txt");
添加一个带有文件对象的requestParams参数用来上传:
File myFile = new File("/path/to/file.png");
RequestParams params = new RequestParams();
params.put("profile_picture", myFile);
} catch(FileNotFoundException e) {}
添加一个带有字节数组的requestParams参数用来上传:
byte[] myByteArray =
RequestParams params = new RequestParams();
params.put("soundtrack", new ByteArrayInputStream(myByteArray), "she-wolf.mp3");
查看以获取更多信息。
使用FileAsyncHttpResponseHandler下载二进制数据
FileAsyncHttpResponseHandler类可以用来获取二进制数据,如图像和其他文件。例如:
AsyncHttpClient client = new AsyncHttpClient();
client.get("/file.png", new FileAsyncHttpResponseHandler( this) {
public void onSuccess(int statusCode, Header[] headers, File response) {
查看以获取更多信息。
添加HTTP基本身份验证信息
一些请求可能在处理使用HTTP基本身份验证请求访问的API服务时需要用户名/密码凭据。你可以使用方法setBasicAuth()提供您的凭据。
对任何主机和领域特定的请求设置用户名/密码。默认情况下,认证范围是任何主机,端口和领域。
AsyncHttpClient client = new AsyncHttpClient();
client.setBasicAuth("username","password/token");
client.get("");
你还可以提供更具体的认证范围(推荐)
AsyncHttpClient client = new AsyncHttpClient();
client.setBasicAuth("username","password", new AuthScope("", 80, AuthScope.ANY_REALM));
client.get("");
查看以获取更多信息。
你可以在真实的设备或模拟器使用提供的示例应用程序测试库。库的示例应用程序实现了所有重要的功能,你可以使用它作为灵感的源泉。
示例应用程序的源代码:
要运行示例应用程序,在它的根克隆android-async-http github库和运行命令:
gradle :sample:installDebug
将在连接的设备上安装示例应用程序,所有示例都会立即工作,如果不是请上传文件错误报告:
下篇文章将会直接进行代码分析。
转载请注明出处
排名:千里之外
(52)(1)(2)(1)(8)(6)(1)(6)(5)(0)(6)开源框架(78)
开源项目链接
-async-http仓库:git clone&
android-async-http主页:
开始使用分析前还是先了解下Android的HTTP一些过往趣事:
HttpClient拥有众多的API,实现稳定,bug很少。
HttpURLConnection是一种多用途、轻量的HTTP客户端,使用它来进行HTTP操作可以适用于大多数的应用程序。HttpURLConnection的API比较简单、扩展容易。不过在Android 2.2版本之前,HttpURLConnection一直存在着一些bug。
比如说对一个可读的InputStream调用close()方法时,就有可能会导致连接池失效了。所以说2.2之前推荐使用HttpClient,2.2之后推荐HttpURLConnection。
好了,那现在话又说回来,在android-async-http中使用的是HttpClient。哎…好像在Volley中分析过Volley对不同版本进行了判断,所以针对不同版本分别使用了HttpClient和HttpURLConnection。还是google牛逼啊!
回过神继续android-async-http吧,不瞎扯了。android-async-http是专门针对Android在Apache的HttpClient基础上构建的异步http连接。所有的请求全在UI(主)线程之外执行,而callback使用了Android的Handler发送消息机制在创建它的线程中执行。
类似Volley一样,使用一个优秀框架之前就是必须得先知道他的特性,如下就是android-async-http的特性:
发送异步http请求,在匿名callback对象中处理response信息;
http请求发生在UI(主)线程之外的异步线程中;
内部采用线程池来处理并发请求;
通过RequestParams类构造GET/POST;
内置多部分文件上传,不需要第三方库支持;
流式Json上传,不需要额外的库;
能处理环行和相对重定向;
和你的app大小相比来说,库的size很小,所有的一切只有90kb;
在各种各样的移动连接环境中具备自动智能请求重试机制;
自动的gzip响应解码;
内置多种形式的响应解析,有原生的字节流,string,json对象,甚至可以将response写到文件中;
永久的cookie保存,内部实现用的是Android的SharedPreferences;
通过BaseJsonHttpResponseHandler和各种json库集成;
支持SAX解析器;
支持各种语言和content编码,不仅仅是UTF-8;
整体操作流程
android-async-http最简单基础的使用只需如下步骤:
创建一个AsyncHttpClient;
(可选的)通过RequestParams对象设置请求参数;
调用AsyncHttpClient的某个get方法,传递你需要的(成功和失败时)callback接口实现,一般都是匿名内部类,实现了AsyncHttpResponseHandler,类库自己也提供许多现成的response handler,你一般不需要自己创建。
AsyncHttpClient与AsyncHttpResponseHandler基础GET体验
AsyncHttpClient类通常用在android应用程序中创建异步GET, POST, PUT和DELETE HTTP请求,请求参数通过RequestParams实例创建,响应通过重写匿名内部类ResponseHandlerInterface方法处理。
如下代码展示了使用AsyncHttpClient与AsyncHttpResponseHandler的基础操作:
AsyncHttpClient client = new AsyncHttpClient();
client.get(&&, new AsyncHttpResponseHandler() {
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
public void onStart() {
super.onStart();
public void onFinish() {
super.onFinish();
public void onRetry(int retryNo) {
super.onRetry(retryNo);
public void onCancel() {
super.onCancel();
public void onProgress(int bytesWritten, int totalSize) {
super.onProgress(bytesWritten, totalSize);
官方推荐AsyncHttpClient静态实例化的封装
注意:官方推荐使用一个静态的AsyncHttpClient,官方示例代码如下:
public class TwitterRestClient {
private static final String BASE_URL = &/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 + relativeU
通过官方这个推荐例子可以发现,我们在用时可以直接通过类名调用需要的请求方法。所以我们可以自己多封装一些不同的请求方法,比如参数不同的方法,下载方法,上传方法等。
RequestParams的基础使用
RequestParams params = new RequestParams();
params.put(&username&, &yanbober&);
params.put(&password&, &123456&);
params.put(&email&, &&);
* Upload a File
params.put(&file_pic&, new File(&test.jpg&));
params.put(&file_inputStream&, inputStream);
params.put(&file_bytes&, new ByteArrayInputStream(bytes));
* url params: &user[first_name]=jesse&user[last_name]=yan&
Map&String, String& map = new HashMap&String, String&();
map.put(&first_name&, &jesse&);
map.put(&last_name&, &yan&);
params.put(&user&, map);
* url params: &what=haha&like=wowo&
Set&String& set = new HashSet&String&();
set.add(&haha&);
set.add(&wowo&);
params.put(&what&, set);
* url params: &languages[]=Java&languages[]=C&
List&String& list = new ArrayList&String&();
list.add(&Java&);
list.add(&C&);
params.put(&languages&, list);
* url params: &colors[]=blue&colors[]=yellow&
String[] colors = { &blue&, &yellow& };
params.put(&colors&, colors);
* url params: &users[][age]=30&users[][gender]=male&users[][age]=25&users[][gender]=female&
List&Map&String, String&& listOfMaps = new ArrayList&Map&String, String&&();
Map&String, String& user1 = new HashMap&String, String&();
user1.put(&age&, &30&);
user1.put(&gender&, &male&);
Map&String, String& user2 = new HashMap&String, String&();
user2.put(&age&, &25&);
user2.put(&gender&, &female&);
listOfMaps.add(user1);
listOfMaps.add(user2);
params.put(&users&, listOfMaps);
* 使用实例
AsyncHttpClient client = new AsyncHttpClient();
client.post(&http://localhost:8080/androidtest/&, params, responseHandler);
JsonHttpResponseHandler带Json参数的POST
JSONObject jsonObject = new JSONObject();
jsonObject.put(&username&, &ryantang&);
StringEntity stringEntity = new StringEntity(jsonObject.toString());
client.post(mContext, &/login&, stringEntity, &application/json&, new JsonHttpResponseHandler(){
public void onSuccess(JSONObject jsonObject) {
super.onSuccess(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
BinaryHttpResponseHandler下载文件
client.get(&http://download/file/test.java&, new BinaryHttpResponseHandler() {
public void onSuccess(byte[] arg0) {
super.onSuccess(arg0);
File file = Environment.getExternalStorageDirectory();
File file2 = new File(file, &down&);
file2.mkdir();
file2 = new File(file2, &down_file.jpg&);
FileOutputStream oStream = new FileOutputStream(file2);
oStream.write(arg0);
oStream.flush();
oStream.close();
} catch (Exception e) {
e.printStackTrace();
Log.i(null, e.toString());
RequestParams上传文件
File myFile = new File(&/sdcard/test.java&);
RequestParams params = new RequestParams();
params.put(&filename&, myFile);
AsyncHttpClient client = new AsyncHttpClient();
client.post(&http://update/server/location/&, params, new AsyncHttpResponseHandler(){
public void onSuccess(int statusCode, String content) {
super.onSuccess(statusCode, content);
} catch(FileNotFoundException e) {
e.printStackTrace();
PersistentCookieStore持久化存储cookie
官方文档里说PersistentCookieStore类用于实现Apache HttpClient的CookieStore接口,可自动将cookie保存到Android设备的SharedPreferences中,如果你打算使用cookie来管理验证会话,这个非常有用,因为用户可以保持登录状态,不管关闭还是重新打开你的app。
文档里介绍了持久化Cookie的步骤:
创建 AsyncHttpClient实例对象;
将客户端的cookie保存到PersistentCookieStore实例对象,带有activity或者应用程序context的构造方法;
任何从服务器端获取的cookie都会持久化存储到myCookieStore中,添加一个cookie到存储中,只需要构造一个新的cookie对象,并且调用addCookie方法;
下面这个例子就是铁证:
AsyncHttpClient client = new AsyncHttpClient();
PersistentCookieStore cookieStore = new PersistentCookieStore(this);
client.setCookieStore(cookieStore);
BasicClientCookie newCookie = new BasicClientCookie(&name&, &value&);
newCookie.setVersion(1);
newCookie.setDomain(&&);
newCookie.setPath(&/&);
cookieStore.addCookie(newCookie);
总结性的唠叨几句
AsyncHttpResponseHandler是一个请求返回处理、成功、失败、开始、完成等自定义的消息的类,如上第一个基础例子中所示。
BinaryHttpResponseHandler是继承AsyncHttpResponseHandler的子类,这是一个字节流返回处理的类,用于处理图片等类。
JsonHttpResponseHandler是继承AsyncHttpResponseHandler的子类,这是一个json请求返回处理服务器与客户端用json交流时使用的类。
AsyncHttpRequest继承自Runnable,是基于线程的子类,用于异步请求类, 通过AsyncHttpResponseHandler回调。
PersistentCookieStore继承自CookieStore,是一个基于CookieStore的子类, 使用HttpClient处理数据,并且使用cookie持久性存储接口。
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:18317次
积分:1691
积分:1691
排名:第16904名
原创:107篇
转载:294篇【图文】第11章Android网络编程(4学时)_百度文库
两大类热门资源免费畅读
续费一年阅读会员,立省24元!
评价文档:
第11章Android网络编程(4学时)
上传于||暂无简介
大小:997.06KB
登录百度文库,专享文档复制特权,财富值每天免费拿!
你可能喜欢android(28)
[摘要:1.简介 Android中收集要求一样平常应用Apache HTTP Client或采纳HttpURLConnect,然则间接应用那两个类库须要写大批的代码才干完成收集post战get要求,而应用android-async-http那个库能够大大的简化操]&
Android中网络请求一般使用Apache HTTP Client或者采用HttpURLConnect,但是直接使用这两个类库需要写大量的代码才能完成网络post和get请求,而使用android-async-http这个库可以大大的简化操作,它是基于Apache’s HttpClient ,所有的请求都是独立在UI主线程之外,通过回调方法处理请求结果,采用android &Handler message 机制传递信息。
(1)采用异步http请求,并通过匿名内部类处理回调结果
(2)http请求独立在UI主线程之外
(3)采用线程池来处理并发请求
(4)采用RequestParams类创建GET/POST参数
(5)不需要第三方包即可支持Multipart file文件上传
(6)大小只有25kb
(7)自动为各种移动电话处理连接断开时请求重连
(8)超快的自动gzip响应解码支持
(9)使用BinaryHttpResponseHandler类下载二进制文件(如图片)
(10) 使用JsonHttpResponseHandler类可以自动将响应结果解析为json格式
(11)持久化cookie存储,可以将cookie保存到你的应用程序的SharedPreferences中
3.使用方法
(1)到官网/android-async-http/下载最新的android-async-http-1.4.9.jar,然后将此jar包添加进Android应用程序 libs文件夹
(2)通过import com.loopj.android.http.*;引入相关类
(3)创建异步请求
[java] view plaincopy
AsyncHttpClient client = new AsyncHttpClient(); &
client.get(&&, new AsyncHttpResponseHandler() { &
& & @Override &
& & public void onSuccess(String response) { &
& & & & System.out.println(response); &
4.建议使用静态的Http Client对象
在下面这个例子,我们创建了静态的http client对象,使其很容易连接到Twitter的API
[java] view plaincopy
import com.loopj.android.http.*; &
public class TwitterRestClient { &
& private static final String BASE_URL = &/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 + relativeU &
然后我们可以很容易的在代码中操作Twitter的API
[java] view plaincopy
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(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); &
& & & & & & } &
& & & & }); &
5. AsyncHttpClient, RequestParams ,AsyncHttpResponseHandler三个类使用方法
(1)AsyncHttpClient
public class AsyncHttpClient extends java.lang.Object
&该类通常用在android应用程序中创建异步GET, POST, PUT和DELETE HTTP请求,请求参数通过RequestParams实例创建,响应通过重写匿名内部类 ResponseHandlerInterface的方法处理。
[java] view plaincopy
AsyncHttpClient client = new AsyncHttpClient(); &
&client.get(&&, new ResponseHandlerInterface() { &
& & &@Override &
& & &public void onSuccess(String response) { &
& & & & &System.out.println(response); &
(2)RequestParams
public class RequestParams extends java.lang.Object&
用于创建AsyncHttpClient实例中的请求参数(包括字符串或者文件)的集合
[java] view plaincopy
RequestParams params = new RequestParams(); &
&params.put(&username&, &james&); &
&params.put(&password&, &123456&); &
&params.put(&email&, &&); &
&params.put(&profile_picture&, new File(&pic.jpg&)); // Upload a File &
&params.put(&profile_picture2&, someInputStream); // Upload an InputStream &
&params.put(&profile_picture3&, new ByteArrayInputStream(someBytes)); // Upload some bytes &
&Map&String, String& map = new HashMap&String, String&(); &
&map.put(&first_name&, &James&); &
&map.put(&last_name&, &Smith&); &
&params.put(&user&, map); // url params: &user[first_name]=James&user[last_name]=Smith& &
&Set&String& set = new HashSet&String&(); // unordered collection &
&set.add(&music&); &
&set.add(&art&); &
&params.put(&like&, set); // url params: &like=music&like=art& &
&List&String& list = new ArrayList&String&(); // Ordered collection &
&list.add(&Java&); &
&list.add(&C&); &
&params.put(&languages&, list); // url params: &languages[]=Java&languages[]=C& &
&String[] colors = { &blue&, &yellow& }; // Ordered collection &
&params.put(&colors&, colors); // url params: &colors[]=blue&colors[]=yellow& &
&List&Map&String, String&& listOfMaps = new ArrayList&Map&String, String&&(); &
&Map&String, String& user1 = new HashMap&String, String&(); &
&user1.put(&age&, &30&); &
&user1.put(&gender&, &male&); &
&Map&String, String& user2 = new HashMap&String, String&(); &
&user2.put(&age&, &25&); &
&user2.put(&gender&, &female&); &
&listOfMaps.add(user1); &
&listOfMaps.add(user2); &
&params.put(&users&, listOfMaps); // url params: &users[][age]=30&users[][gender]=male&users[][age]=25&users[][gender]=female& &
&AsyncHttpClient client = new AsyncHttpClient(); &
&client.post(&&, params, responseHandler); &
(3)public class AsyncHttpResponseHandler extends java.lang.Object implements ResponseHandlerInterface
用于拦截和处理由AsyncHttpClient创建的请求。在匿名类AsyncHttpResponseHandler中的重写 onSuccess(int, org.apache.http.Header[], byte[])方法用于处理响应成功的请求。此外,你也可以重写 onFailure(int, org.apache.http.Header[], byte[], Throwable), onStart(), onFinish(), onRetry() 和onProgress(int, int)方法
[java] view plaincopy
AsyncHttpClient client = new AsyncHttpClient(); &
&client.get(&&, new AsyncHttpResponseHandler() { &
& & &@Override &
& & &public void onStart() { &
& & & & &// Initiated the request &
& & &@Override &
& & &public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { &
& & & & &// Successfully got a response &
& & &@Override &
& & &public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) &
& & & & &// Response failed :( &
& & &@Override &
& & &public void onRetry() { &
& & & & &// Request was retried &
& & &@Override &
& & &public void onProgress(int bytesWritten, int totalSize) { &
& & & & &// Progress notification &
& & &@Override &
& & &public void onFinish() { &
& & & & &// Completed the request (either success or failure) &
6.利用PersistentCookieStore持久化存储cookie
PersistentCookieStore类用于实现Apache HttpClient的CookieStore接口,可以自动的将cookie保存到Android设备的SharedPreferences中,如果你打算使用cookie来管理验证会话,这个非常有用,因为用户可以保持登录状态,不管关闭还是重新打开你的app
(1)首先创建 AsyncHttpClient实例对象
[java] view plaincopy
AsyncHttpClient myClient = new AsyncHttpClient(); &
(2)将客户端的cookie保存到PersistentCookieStore实例对象,带有activity或者应用程序context的构造方法
[java] view plaincopy
PersistentCookieStore myCookieStore = new PersistentCookieStore(this); &
myClient.setCookieStore(myCookieStore); &
(3)任何从服务器端获取的cookie都会持久化存储到myCookieStore中,添加一个cookie到存储中,只需要构造一个新的cookie对象,并且调用addCookie方法
[java] view plaincopy
BasicClientCookie newCookie = new BasicClientCookie(&cookiesare&, &awesome&); &
newCookie.setVersion(1); &
newCookie.setDomain(&&); &
newCookie.setPath(&/&); &
myCookieStore.addCookie(newCookie); &
7.利用RequestParams上传文件
类RequestParams支持multipart file 文件上传
(1)在RequestParams 对象中添加InputStream用于上传
[java] view plaincopy
InputStream myInputStream = &
RequestParams params = new RequestParams(); &
params.put(&secret_passwords&, myInputStream, &passwords.txt&); &
(2)添加文件对象用于上传
[java] view plaincopy
File myFile = new File(&/path/to/file.png&); &
RequestParams params = new RequestParams(); &
& & params.put(&profile_picture&, myFile); &
} catch(FileNotFoundException e) {} &
(3)添加字节数组用于上传
[java] view plaincopy
byte[] myByteArray = &
RequestParams params = new RequestParams(); &
params.put(&soundtrack&, new ByteArrayInputStream(myByteArray), &she-wolf.mp3&); &
8.用BinaryHttpResponseHandler下载二进制数据
[java] view plaincopy
BinaryHttpResponseHandler用于获取二进制数据如图片和其他文件 &
AsyncHttpClient client = new AsyncHttpClient(); &
String[] allowedContentTypes = new String[] { &image/png&, &image/jpeg& }; &
client.get(&/file.png&, new BinaryHttpResponseHandler(allowedContentTypes) { &
& & @Override &
& & public void onSuccess(byte[] fileData) { &
& & & & // Do something with the file &
------------------------------------------------------------------------------------------
android-async-http 开源框架可以使我们轻松地获取网络数据或者向服务器发送数据,最关键的是,它是异步框架,在底层使用线程池处理并发请求,效率很高,使用又特别简单。
& & 以往我们在安卓上做项目,比如要下载很多图片、网页或者其他的资源,多数开发者会选择一个线程一个下载任务这种模型,因为安卓自带的 AndroidHttpClient 或者 java 带的 java.net.URL ,默认都是阻塞式操作。这种模型效率不高,对并发要求高的 APP 来讲,并不适用。有的人会选择使用 nio 自己实现,代码复杂度又很高。
& & AsyncHttpClient 作为 android-async-http 框架的一个核心应用类,使用简单,可以处理文本、二进制等各种格式的 web 资源。下面提供一些代码来看如何使用:
[java] view plaincopy在CODE上查看代码片派生到我的代码片
public class Downloader { &
& & public static AsyncHttpClient mHttpc = new AsyncHttpClient(); &
& & public static String TAG = &Downloader&; &
& & public void downloadText(String uri){ &
& & & & mHttpc.get(uri, null, new AsyncHttpResponseHandler(){ &
& & & & & & @Override &
& & & & & & public void onSuccess(String data){ &
& & & & & & & & Log.i(TAG, &downloaded, thread id & + Thread.currentThread().getId()); &
& & & & & & & & // TODO: do something on &
& & & & & & } &
& & & & & & @Override &
& & & & & & public void onFailure(Throwable e, String data){ &
& & & & & & & & Log.i(TAG, &download failed.&); &
& & & & & & & & // TODO: error proceed &
& & & & & & } &
& & & & }); &
& & public void downloadImage(String uri, String savePath){ &
& & & & mHttpc.get(uri, new ImageResponseHandler(savePath)); &
& & public class ImageResponseHandler extends BinaryHttpResponseHandler{ &
& & & & private String mSaveP &
& & & & &&
& & & & public ImageResponseHandler(String savePath){ &
& & & & & & super(); &
& & & & & & mSavePath = saveP &
& & & & } &
& & & & @Override &
& & & & public void onSuccess(byte[] data){ &
& & & & & & Log.i(TAG, &download image, file length & + data.length); &
& & & & & & // TODO: save image , do something on image &
& & & & } &
& & & & @Override &
& & & & public void onFailure(Throwable e, String data){ &
& & & & & & Log.i(TAG, &download failed&); &
& & & & & & // TODO : error proceed &
& & & & } &
& & 上面的代码演示了如何使用 AsyncHttpResponseHandler 和 BinaryHttpResponseHandler ,相信 AsyncHttpClient &会给大家带来很大的便利。
AsyncHttpClient框架下载地址:/android-async-http/
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:3104次
排名:千里之外
原创:14篇
转载:19篇
(1)(3)(6)(6)(2)(1)(10)(2)(2)}

我要回帖

更多关于 android ndk 网络编程 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信