Android Asynchronous Http Client
asyncHttpCliet 是apache http 封装后的用于网络请求数据、上传数据的异步类。
基本的用法:
创建一个AsyncHttpClient后,可以使用get的方法和post方法,分别就是对应的get和post的方式访问。
下面分别对访问和上传进行说明。
(一)一般数据访问:
AsyncHttpClient client = new AsyncHttpClient();
try {
RequestParams params = new RequestParams();
params.put("keyword", URLEncoder.encode("你好", "UTF-8"));
client.get("http://client.azrj.cn/json/cook/cook_list.jsp?type=1&p=2&size=10", params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String response) {
L.i(getClass(), "response:"+response);
}
@Override
public void onStart() {
super.onStart();
L.i(getClass(), "onStart()");
}
@Override
public void onFinish() {
super.onFinish();
L.i(getClass(), "onFinish()");
}
@Override
public void onFailure(int arg0, Header[] arg1, byte[] arg2,
Throwable arg3) {
L.i(getClass(), "onFailure()");
super.onFailure(arg0, arg1, arg2, arg3);
}
});
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
只需将onSuccess函数稍作修改即可。
@Override
public void onSuccess(String response) {
L.i(getClass(), "response:"+response);
try {
JSONObject jObject = new JSONObject(response);
L.i(getClass(), "jObject:"+jObject.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
File图片数据访问:
@Override
public void onSuccess(int code, Header[] headers, byte[] bytes) {
super.onSuccess(code, headers, bytes);
File file = new File(path);
FileOutputStream oStream = new FileOutputStream(file);
oStream.write(bytes);
oStream.flush();
oStream.close();
}
(二)一般数据上传:
设置好params就行。
RequestParams params = new RequestParams();
params.put("key", "value");
params.put("more", "data");
文件数据上传:
只需修改param里的数据即可:
方法.1 流方法
InputStream myInputStream = blah;
RequestParams params = new RequestParams();
params.put("secret_passwords", myInputStream, "passwords.txt");
方法.2 文件方法File myFile = new File("/path/to/file.png");
RequestParams params = new RequestParams();
try {
params.put("profile_picture", myFile);
} catch(FileNotFoundException e) {}
方法.3 字节流方法,针对数据大的如MP3byte[] myByteArray = blah;
RequestParams params = new RequestParams();
params.put("soundtrack", new ByteArrayInputStream(myByteArray), "she-wolf.mp3");
最后简单的介绍一下async-http的cookie的操作:
绑定cookie
PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
myClient.setCookieStore(myCookieStore);
设置cookie的参数BasicClientCookie newCookie = new BasicClientCookie("cookiesare", "awesome");
newCookie.setVersion(1);
newCookie.setDomain("mydomain.com");
newCookie.setPath("/");
myCookieStore.addCookie(newCookie);
这是官网:http://loopj.com/android-async-http/