android-async-http是基于Apache HttpClient库之上的一个异步网络请求处理库,网络处理均基于Android的feiUI线程,通过回调方法处理请求结果,目前非常火的应用Instagram就是用的这个网络请求库。
其主要特征如下:
处理异步HTTP请求,并通过匿名内部类处理回调结果,Http异步请求均位于非UI线程,不会阻塞UI操作,通过线程池处理并发请求文件上传、下载,响应结果自动打包JSON格式,自动处理连接断开时请求重连。
该类库的jar包官网下载地址:http://loooj.com/android.async.http/
这里是我下载好的类库地址:http://download.csdn.net/detail/yabaj/9409216
下面是运用android-async-http的一些小例子:
◆普通的get请求
//测试AndroidAsyncHttp的get请求
String url = "http://192.168.1.102:8080/TestAndroid/testServlet?name=zhangsan&age=23";
AsyncHttpClient client = new AsyncHttpClient();
client.get(getApplicationContext(), url, new AsyncHttpResponseHandler() {
/*
* response:服务器返回的数据
* @see com.loopj.android.http.AsyncHttpResponseHandler#onSuccess(int, org.apache.http.Header[], byte[])
*/
@Override
public void onSuccess(int arg0, Header[] header, byte[] response) {
// TODO Auto-generated method stub
Log.e("服务器返回", new String(response));
}
@Override
public void onFailure(int arg0, Header[] header, byte[] response, Throwable exception) {
// TODO Auto-generated method stub
Log.e("连接异常", exception.toString());
}
});
◆文件上传(这里是post请求)
这里是服务器端关键代码:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
System.out.println("进入post方法");
uploadFile(request,response);
}
/**
* 上传文件处理
* @param request
* @param response
*/
private void uploadFile(HttpServletRequest request,
HttpServletResponse response) {
// TODO Auto-generated method stub
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(factory);
try {
List<FileItem> list = fileUpload.parseRequest(new ServletRequestContext(request));
for (FileItem fileItem : list) {
if(fileItem.isFormField()){
String name = fileItem.getFieldName();
if("description".equals(name)){
String des = new String(fileItem.getString().getBytes("iso8859-1"));
System.out.println("description:" + des);
}
}else{
//上传到根目录
String path = getServletContext().getRealPath("/");
String name = fileItem.getName();
System.out.println("name:" + name);
String extName = name.substring(name.lastIndexOf("."));
String uuid = UUID.randomUUID().toString();
name = uuid + extName;
path = path + name;
System.out.println("path: " + path);
fileItem.write(new File(path));
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
客户端:
//测试AndroidAsyncHttp的文件上传 (post)
String url = "http://192.168.1.102:8080/TestAndroid/testServlet";
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
//添加文件流的方式
InputStream stream = getResources().openRawResource(R.raw.bg02);
params.put("filename", stream, "test_upload.jpg");
//添加文件对象的方式
// File myFile = new File("/Lesson01/res/drawable-hdpi/bg01.jpg");
// try {
// params.put("filename", myFile);
// } catch (FileNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
client.post(url, params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
// TODO Auto-generated method stub
Log.e("结果回调", "上传成功");
}
@Override
public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
// TODO Auto-generated method stub
Log.e("结果回调", "上传失败");
}
});
客户端运行结果:
服务器运行结果:
◆文件下载 (这里是get请求)
//测试AndroidAsyncHttp的文件下载 (get)
String url = "http://192.168.1.102:8080/TestAndroid/image/bg02.jpg";
AsyncHttpClient client = new AsyncHttpClient();
client.get(url, new FileAsyncHttpResponseHandler(this) {
@Override
public void onSuccess(int arg0, Header[] arg1, File file) {
// TODO Auto-generated method stub
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/" +file.getName() + ".jpg";
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(file);
fos = new FileOutputStream(path);
byte[] buffer = new byte[1024];
int len = -1;
while((len = fis.read(buffer)) != -1){
fos.write(buffer, 0 ,len);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
fis.close();
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Log.e("结果回调", "下载成功");
}
@Override
public void onFailure(int arg0, Header[] arg1, Throwable arg2, File file) {
// TODO Auto-generated method stub
Log.e("结果回调", "下载失败");
}
});
运行结果:
◆传递json数据:
服务器端部分代码:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
System.out.println("进入post方法");
InputStream is = request.getInputStream();
byte [] buffer = new byte[1024];
int len = -1;
StringBuffer sb = new StringBuffer();
while((len = is.read(buffer)) != -1){
sb.append(new String(buffer, 0, len, "utf-8"));
}
System.out.println(sb.toString());
PrintWriter writer = response.getWriter();
String json = "{'info':'Post','content':'name,age send 成功'}";
writer.write(json);
}
客户端:
//测试AndroidAsyncHttp的json数据传递(Post)
String url = "http://192.168.0.159:8080/TestAndroid/testServlet";
AsyncHttpClient client = new AsyncHttpClient();
JSONObject obj = new JSONObject();
StringEntity entity = null;
try {
obj.put("name", "zhangsan");
obj.put("age", 23);
entity = new StringEntity(obj.toString(), "utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
client.post(getApplicationContext(), url, entity, "application/json", new JsonHttpResponseHandler(){
@Override
public void onSuccess(int statusCode, Header[] headers,
JSONObject response) {
// TODO Auto-generated method stub
super.onSuccess(statusCode, headers, response);
Log.e("结果回调", response.toString());
}
});
服务器端运行结果:
客户端: