android-async-http是基于Apache HttpClient库之上的一个异步网络请求处理库,网络处理均基于Android的非UI线程,通过回调方法处理请求结果,目前非常火的应用Instagram就是用的这个网络请求库。
其主要特征如下:处理异步Http请求,并通过匿名内部类处理回调结果,Http异步请求均位于非UI线程,不会阻塞UI操作,通过线程池处理并发请求处理文件上传、下载,响应结果自动打包JSON格式自动处理连接断开时请求重连。
官方下载:http://looopj.com/android-async-http/
发送一个简单的GET请求
public void sendSimpleGetClick(View view){
AsyncHttpClient client=new AsyncHttpClient();
client.get("http://www.baidu.com", new AsyncHttpResponseHandler() {//处理普通文本内容
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
//200 ok
String info=new String(responseBody);
System.out.println(info);
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
System.out.println("error:"+new String(responseBody));
}
});
}
创建RequestParams添加请求参数:
RequestParams params=new RequestParams();
params.put("key","value");
params.put("more","value");
添加一个参数可使用:
RequestParams params=new RequestParams("single","value");
使用Map添加参数:
HashMap paramMap=new HashMap();
paramMap.put("key","value");
RequestParams params=new RequestParams(paramMap);
具体代码如下
public void sendSimpleParamsClick(View view){
AsyncHttpClient client=new AsyncHttpClient();
RequestParams params=new RequestParams();
params.put("cityname","朝阳");
client.post(this, "http://apis.baidu.com/apistore/weatherservice/citylist", params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
System.out.println(new String(responseBody));
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
System.out.println(new String(responseBody));
}
});
}
上传文件
添加一个文件流
InputStream myInputStream=blah;
RequestParams params=new RequestParams();
params.put("secret_passwords",myInputStream,"password.txt");
添加一个文件对象
File myFile=new File("/path/to/file.png");
RequestParams params=new RequestParams();
try {
params.put("timg.jpg",myFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
添加一个字节数组
byte[] myByteArray=blah;
RequestParams params=new RequestParams();
params.put("soundtrack",new ByteArrayInputStream(myByteArray),"she-wilf.mp3");
具体代码
public void upLoadClick(View view){
AsyncHttpClient client=new AsyncHttpClient();
RequestParams params=new RequestParams();
params.put("description","风景图片");
//设置文件
try {
//获得文件路径
String path= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+"/timg.jpg";
params.put("timg.jpg",new File(path),"image/jpeg");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
client.post(this, url, params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
System.out.println(new String(responseBody));
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
System.out.println(new String(responseBody));
}
});
}
下载文件
public void downLoadClick(View view){
AsyncHttpClient client=new AsyncHttpClient();
client.get("http://b.hiphotos.baidu.com/image/pic/item/4b90f603738da977f86d8b56be51f8198618e309.jpg", new FileAsyncHttpResponseHandler(this) {
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, File file) {
//error
}
@Override
public void onSuccess(int statusCode, Header[] headers, File file) {
//success
System.out.println(file.getAbsolutePath());
String path=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+"/4b90f603738da977f86d8b56be51f8198618e309.jpg";
try {
InputStream inputStream=new FileInputStream(file);
OutputStream outputStream=new FileOutputStream(path);
byte[] bytes=new byte[100];
int len=-1;
while((len=inputStream.read(bytes))!=-1){
outputStream.write(bytes,0,len);
outputStream.flush();
}
outputStream.close();
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("DownLoad Complete");
}
});
}
带Json参数的POST
public void jsonClick(View view){
AsyncHttpClient client=new AsyncHttpClient();
String url="http://api.com/login";
JSONObject jsonObject=new JSONObject();
try {
jsonObject.put("username", "ryantang");
StringEntity entity=new StringEntity(jsonObject.toString());
client.post(this,url,entity,"application/json",new JsonHttpResponseHandler(){
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
System.out.println(response.toString());
}
});
} catch (JSONException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}