首先在GitHub上下载异步Http框架代码以及相关文档:

android异步Http框架-LMLPHP

将jar包放入lib包中即可;

接下来分别实现get、post、文件上传功能实现:

代码实现如下:

AsyncHttpClient client = new AsyncHttpClient();
String path = "url连接";
/**
* Http--get请求
*/
client.get(path, new AsyncHttpResponseHandler(){
@Override
@Deprecated
public void onSuccess(String content) {
super.onSuccess(content);
Toast.makeText(MainActivity.this, content, Toast.LENGTH_SHORT).show();
} @Override
@Deprecated
public void onFailure(Throwable error, String content) {
// TODO Auto-generated method stub
super.onFailure(error, content);
Toast.makeText(MainActivity.this, content, Toast.LENGTH_SHORT).show();
}
}); /**
* http--post
*/
RequestParams params = new RequestParams();
params.put("account", "测试用户");
params.put("password", "12315");
client.post(path, params, new AsyncHttpResponseHandler(){
@Override
@Deprecated
public void onSuccess(String content) {
super.onSuccess(content);
Toast.makeText(MainActivity.this, content, Toast.LENGTH_SHORT).show();
}
@Override
@Deprecated
public void onFailure(Throwable error, String content) {
// TODO Auto-generated method stub
super.onFailure(error, content);
Toast.makeText(MainActivity.this, content, Toast.LENGTH_SHORT).show();
}
});
/**
* Http--文件上传
*/
String path1 = "/sdcard/p.jpg";
File file = new File(path1);
try {
params.put("profile_picture", file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
client.post("上传接口url地址",params, new AsyncHttpResponseHandler(){ @Override
@Deprecated
public void onFailure(Throwable error, String content) {
super.onFailure(error, content);
Toast.makeText(MainActivity.this, content, Toast.LENGTH_SHORT).show();
} @Override
@Deprecated
public void onSuccess(String content) {
Toast.makeText(MainActivity.this, content, Toast.LENGTH_SHORT).show();
} } );

android_async_http框架将常用的Http协议进行封装,简化了开发者的操作,并且具有Gzip压缩数据的功能,

项目链接:https://github.com/loopj/android-async-http

通过线程池去处理资源访问
GET/ POSTparams建设者(RequestParams)
实现多重文件上传并且没有额外的第三方库
jar包只有19Kb,很小
优化网络请求,支持Gzip

虽然是比较优秀的http框架,但是在实际使用过程中也出现了一下不理想的问题,所以不建议使用。

更多内容:http://www.apkbus.com/blog-87624-55718.html

05-08 08:12