async-http-client库是一个基于回调函数的Http异步通信客户端Android组件,是在Apache的HttpClient库的基础上开发构建而成的。

Eclipse使用:导入android-async-http-1.4.4.jar 包, 点击下载

AndroidStudio: gradle中引入 compile 'com.loopj.android:android-async-http:1.4.8'

功能特色

  • 利用版4.3.6上游HttpClient代替Android提供defaulthttpclient
  • 兼容AndroidAPI 23高
  • 做异步HTTP请求处理的响应匿名回调
  • HTTP请求发生UI线程之外
  • 请求使用线程池限制并发资源使用情况
  • get /后参数生成器( RequestParams )
  • 多文件上传没有额外的第三方库
  • JSON上传流没有额外的图书馆
  • 处理循环和相对重定向
  • 小的开销给你的应用程序只90kb一切
  • 自动智能请求重试次数质量不一的移动连接优化
  • 自动gzip响应解码速度超快的请求支持
  • 二进制协议通信binaryhttpresponsehandler
  • 内置的响应分析JSON与jsonhttpresponsehandler
  • 节能反应直接进入文件fileasynchttpresponsehandler
  • 大的持久性Cookie,保存cookie到你的应用程序的SharedPreferences
  • 杰克逊JSON集成,gson或其他JSON序列化库(德)basejsonhttpresponsehandler
  • 与SAX解析器支持saxasynchttpresponsehandler
  • 语言和内容编码的支持,不仅仅是UTF-8

效果图:

 public class MainActivity extends Activity implements OnClickListener {

     public static AsyncHttpClient mHttpc = new AsyncHttpClient();

     private TextView mTextView;

     @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_asynchttpclict);
initView();
} private void initView() {
findViewById(R.id.btn1).setOnClickListener(this);
findViewById(R.id.btn2).setOnClickListener(this);
findViewById(R.id.btn3).setOnClickListener(this);
findViewById(R.id.btn4).setOnClickListener(this);
mTextView=(TextView) findViewById(R.id.Text);
} @Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn1:
showHttpGet1();
break;
case R.id.btn2:
showHttpGet2("https://www.baidu.com");
break;
case R.id.btn3:
showHttpGet3();
break;
case R.id.btn4:
showHttpPost();
break;
case R.id.btn5: case R.id.btn6: default:
break;
} } private void showHttpGet1() {
AsyncHttpClient client = new AsyncHttpClient();
client.get("https://www.baidu.com", new AsyncHttpResponseHandler() {
@Override
public void onStart() { // 请求启动 请求前
} @Override
public void onSuccess(int statusCode, Header[] headers,
byte[] responseBody) { // 请求成功
StringBuffer result = new StringBuffer("");
int length = responseBody.length;
for (int i = 0; i < length; i++) {
result.append((char) (responseBody[i] & 0xff));
}
Toast.makeText(MainActivity.this, "结果:" + result.toString(), 2)
.show();
mTextView.setText("结果:" +result.toString());
} @Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) // 请求失败
{ } public void onRetry() { // 重试 } @Override
public void onProgress(int bytesWritten, int totalSize) { // 请求进度 } @Override
public void onFinish() { // 请求完成 }
});
} public void showHttpGet2(String uri) {
mHttpc.get(uri, null, new AsyncHttpResponseHandler() { // 请求失败
@Override
public void onFailure(int arg0, Header[] arg1, byte[] arg2,
Throwable arg3) {
} @Override
public void onSuccess(int arg0, Header[] arg1,
byte[] responseBody) {
StringBuffer result = new StringBuffer("");
int length = responseBody.length;
for (int i = 0; i < length; i++) {
result.append((char) (responseBody[i] & 0xff));
}
Toast.makeText(MainActivity.this,
"结果:" + result.toString(), 2).show();
mTextView.setText("结果:" +result.toString());
}
});
} private void showHttpGet3() {
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("q", "test");
params.put("showapi_appid", "11548");
// 当前时间
params.put("showapi_timestamp", "20160511151954");
params.put("showapi_sign", "bb1d15ab7ce646ec87cc89d684ca4bcb");
client.get("https://route.showapi.com/32-9", params,
new TextHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
String response) {
Toast.makeText(MainActivity.this,
"结果:" + response.toString(), 2).show();
mTextView.setText("结果:" +response.toString());
} @Override
public void onFailure(int statusCode, Header[] headers,
String responseBody, Throwable error) {
Log.i("ERROR", error.toString());
}
});
} /*
* 获得字符串
*/
public void showHttpPost() {
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("q", "test");
params.put("showapi_appid", "11548");
// 当前时间
params.put("showapi_timestamp", "20160511151954");
params.put("showapi_sign", "bb1d15ab7ce646ec87cc89d684ca4bcb");
client.post("https://route.showapi.com/32-9", params,
new AsyncHttpResponseHandler() { @Override
public void onFailure(int arg0, Header[] arg1,
byte[] responseBody, Throwable arg3) { } @Override
public void onSuccess(int arg0, Header[] arg1,
byte[] responseBody) {
StringBuffer result = new StringBuffer("");
int length = responseBody.length;
for (int i = 0; i < length; i++) {
result.append((char) (responseBody[i] & 0xff));
}
Toast.makeText(MainActivity.this,
"结果:" + result.toString(), 2).show();
mTextView.setText("结果:" +result.toString());
}
}); } /**
* 上传单个文件
*/
private void showFile() {
File myFile = new File("filePath");// filePath--->文件路径
RequestParams params = new RequestParams();
try {
params.put("time", "20160511151954");
params.put("sign", "bb1d15ab7ce646ec87cc89d684ca4bcb");
params.put("filename", myFile);
AsyncHttpClient client = new AsyncHttpClient();
client.post("url", params, new AsyncHttpResponseHandler() { @Override
public void onFailure(int arg0, Header[] arg1, byte[] arg2,
Throwable arg3) { } @Override
public void onSuccess(int arg0, Header[] arg1, byte[] arg2) { }
});
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/***
* 多个文件上传
*
* @param sendFilesPath
*/
public void uploadFile(ArrayList<String> sendFilesPath) {
if (sendFilesPath.size() == 0)
return; String strUploadFile = "";
AsyncHttpClient client = new AsyncHttpClient();
client.setURLEncodingEnabled(false); RequestParams params = new RequestParams();
params.put("time", "20160511151954");
params.put("sign", "bb1d15ab7ce646ec87cc89d684ca4bcb");
// 批量上传
for (int i = 0; i < sendFilesPath.size(); i++) {
File myFile = new File(sendFilesPath.get(i));
try {
params.put(myFile.getName(), myFile);
} catch (FileNotFoundException e1) {
continue;
}
} client.setTimeout(10000);
client.post(strUploadFile, params, new AsyncHttpResponseHandler() { @Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable arg3) {
Log.i("Show", "上传失败");
} @Override
public void onSuccess(int statusCode, Header[] headers,
byte[] responseBody) {
Log.i("Show", "上传成功");
} @Override
public void onProgress(int bytesWritten, int totalSize) {
super.onProgress(bytesWritten, totalSize);
int count = (int) ((bytesWritten * 1.0 / totalSize) * 100);
// 上传进度显示
Log.i("Show", "上传进度显示:" + count); } @Override
public void onRetry(int retryNo) {
super.onRetry(retryNo);
// 返回重试次数
}
});
} }

记得加网络权限

<uses-permission android:name="android.permission.INTERNET"/>

源码点击下载:https://github.com/DickyQie/android-network-request

最新文章

  1. LR12.53—第2课:准备脚本重播
  2. sharepoint 弹出窗口
  3. Head First 设计模式 --3 装饰者模式 开闭原则
  4. S1700
  5. Teradata(不同date输出要求;表类型)
  6. SQL injection
  7. jquery取消事件冒泡和取消默认行为
  8. 李洪强iOS开发之OC常见错误汇总
  9. C参数计算
  10. (组合数学3.1.1.2)UVA 10098 Generating Fast(使用字典序思想产生所有序列)
  11. mobile web曾经的踩过坑
  12. POJ2112Optimal Milking(二分法+floyd最短+网络流量)
  13. web server性能优化浅谈
  14. JVM 组成以及各部分作用
  15. C++ STL常用容器浅析
  16. Dell3470无法开机或开机黑屏情况下检测屏幕是否正常
  17. 软件推荐-c#绘图插件echart
  18. java的类属性默认有this 但容易与参数重名 所以需要显性的加上this 以分区别
  19. LOJ.114.K大异或和(线性基)
  20. FATAL bad indentation of a mapping entry at line 83, column 3: branch: master 已解决;

热门文章

  1. 【转】Redis之发布 订阅模式
  2. vue的双向数据绑定原理
  3. linux常用命令:ifconfig 命令
  4. Linux服务器配置---安装telnet
  5. Python入门之实现简单的购物车功能
  6. P3868 [TJOI2009]猜数字
  7. P3501 [POI2010]ANT-Antisymmetry
  8. CSS3实现小黄人动画
  9. UVa 11082 Matrix Decompressing - 网络流
  10. 使用volley来json解析