android-async-http实现下载和上传
2018-07-20 来源:open-open
android-async-http,是一个android异步网络数据请求框架,网络处理均基于Android的非UI线程,通过回调方法处理请求结果。本篇简单介绍一下它的用法,分别实现上传和下载文件的功能。
一.android-async-http简介
-
开源项目android-async-http地址:
https://github.com/loopj/android-async-http -
android-async-http核心组件:
a). AsyncHttpResponseHandler ——这是一个请求返回处理,成功,失败,开始,完成,等自定义的消息的类;
b). BinaryHttpResponseHandler extends AsyncHttpResponseHandler ——继承AsyncHttpResponseHandler的子类,这是一个字节流返回处理的类, 该类用于处理图片等类;
c). JsonHttpResponseHandler extends AsyncHttpResponseHandler ——继承AsyncHttpResponseHandler的子类,这是一个json请求返回处理服务器与客户端用json交流时使用的类;
d). AsyncHttpRequest implements Runnable ——基于线程的子类,用于 异步请求类, 通过AsyncHttpResponseHandler回调。
e). PersistentCookieStore implements CookieStore ——这是一个基于CookieStore的子类, 使用HttpClient处理数据,并且使用cookie持久性存储接口。f). RequestParams ——封装了参数处理 例如:
RequestParams params = new RequestParams(); params.put("uid", "00001"); params.put("password", "111111");
核心操作类:
a). RetryHandler implements HttpRequestRetryHandler——这是一个多个线程同步处理的类;
b). SerializableCookie implements Serializable——这是操作cookie 放入/取出数据的类;
c). SimpleMultipartEntity implements HttpEntity——用于处理多个请求实体封装;
d). SyncHttpClient extends AsyncHttpClient——同步客户端请求的类;
e). AsyncHttpClient——异步客户端请求的类。
二.android-async-http实践
- HttpClientUtil封装类的实现:
这个class对AsyncHttpClient进行了封装。
public class HttpClientUtil { // 实例话对象 private static AsyncHttpClient client = new AsyncHttpClient(); static { client.setTimeout(11000); // 设置链接超时,如果不设置,默认为10s } public static AsyncHttpClient getClient() { return client; } // 用一个完整url获取一个string对象 public static void get(String urlString, AsyncHttpResponseHandler res) { client.get(urlString, res); } // url里面带参数 public static void get(String urlString, RequestParams params, AsyncHttpResponseHandler res) { client.get(urlString, params, res); } // 不带参数,获取json对象或者数组 public static void get(String urlString, JsonHttpResponseHandler res) { client.get(urlString, res); } // 带参数,获取json对象或者数组 public static void get(String urlString, RequestParams params, JsonHttpResponseHandler res) { client.get(urlString, params, res); } // 下载数据使用,会返回byte数据 public static void get(String uString, BinaryHttpResponseHandler bHandler) { client.get(uString, bHandler); } //多个url? public static void get(String urlString, RequestParams params, BinaryHttpResponseHandler bHandler) { client.get(urlString, params, bHandler); } //post public static void post(String urlString, RequestParams params, ResponseHandlerInterface bHandler) { client.post(urlString, params, bHandler); }
2. MyImageDownLoader的实现:
提供了下载图片的函数
public class MyImageDownLoader { private static final String TAG = "MyImageDownLoader"; Context mContext; public interface DownLoaderListener { public void onResult(int res, String s); } public MyImageDownLoader() { } //download image public void downloadImage(String uri, String savePath, DownLoaderListener downLoaderListener){ // 指定文件类型 String[] allowedContentTypes = new String[] { "image/png", "image/jpeg" }; HttpClientUtil.get(uri, new ImageResponseHandler(allowedContentTypes,savePath, downLoaderListener)); } public class ImageResponseHandler extends BinaryHttpResponseHandler{ private String[] allowedContentTypes; private String savePathString; DownLoaderListener mDownLoaderListener; public ImageResponseHandler(String[] allowedContentTypes, String path, DownLoaderListener downLoaderListener){ super(); this.allowedContentTypes = allowedContentTypes; savePathString = path; mDownLoaderListener = downLoaderListener; } @Override public void onSuccess(int statusCode, Header[] headers, byte[] binaryData) { Log.i(TAG, " statusCode=========" + statusCode); Log.i(TAG, " statusCode=========" + headers); Log.i(TAG, " statusCode====binaryData len=====" + binaryData.length); if (statusCode == 200 && binaryData!=null && binaryData.length > 0) { boolean b = saveImage(binaryData,savePathString); if (b) { mDownLoaderListener.onResult(0, savePathString); } else { //fail mDownLoaderListener.onResult(-1, savePathString); } } } @Override public void onFailure(int statusCode, Header[] headers, byte[] binaryData, Throwable error) { Log.i(TAG, "download failed"); } private boolean saveImage(byte[] binaryData, String savePath) { Bitmap bmp = BitmapFactory.decodeByteArray(binaryData, 0, binaryData.length); Log.i(TAG,"saveImage==========" + savePath); File file = new File(savePath); // 压缩格式 CompressFormat format = Bitmap.CompressFormat.JPEG; // 压缩比例 int quality = 100; try { if (file.createNewFile()){ OutputStream stream = new FileOutputStream(file); // 压缩输出 bmp.compress(format, quality, stream); stream.close(); return true; } } catch (IOException e) { Log.i(TAG,"saveImage====003======" + savePath); e.printStackTrace(); } Log.i(TAG,"saveImage====004======" + savePath); return false; } } }
3. HttpAsyncUploader的实现:
/** * 异步上传单个文件 */ public class HttpAsyncUploader { private static final String TAG = "HttpAsyncUploader"; Context mContext; public HttpAsyncUploader() { } public void uploadFile(String uri, String path) { File file = new File(path); RequestParams params = new RequestParams(); try { params.put("image", file, "application/octet-stream"); AsyncHttpClient client = new AsyncHttpClient(); HttpClientUtil.post(path, params, new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { Log.i(TAG, " statusCode=========" + statusCode); Log.i(TAG, " statusCode=========" + headers); Log.i(TAG, " statusCode====binaryData len====="+ responseBody.length); } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { Log.i(TAG, " statusCode=========" + statusCode); Log.i(TAG, " statusCode=========" + headers); Log.i(TAG, " statusCode====binaryData len====="+ responseBody.length); Log.i(TAG," statusCode====error====="+ error.getLocalizedMessage()); } }); } catch (FileNotFoundException e) { } } }
4. 调用方法:仅以MyImageDownLoader 来举例说明。
1)MyImageDownLoader 测试函数(在activity中实现):
private static String URL_PHOTO = "http://img001.us.expono.com/100001/100001-1bc30-2d736f_m.jpg"; private void downloadTest() { String url =URL_PHOTO; String fileName = "" + System.currentTimeMillis() + ".jpg"; String savePath = mContext.getCacheDir() + File.separator + fileName; MyImageDownLoader mMyImageDownLoader = new MyImageDownLoader(); // 开始异步下载 mMyImageDownLoader.downloadImage( url, savePath, new DownLoaderListener() { @Override public void onResult(int res, String s) { Log.i(TAG,"onResult====res===" + res); Log.i(TAG, "onResult====s===" + s); if (res == 0) { // 下载成功 Toast.makeText(mContext, "download success!", Toast.LENGTH_LONG).show(); } else { // 下载photo失败 Toast.makeText(mContext, "download fail!", Toast.LENGTH_LONG).show(); } } }); }
5 项目demo地址:
https://github.com/ranke/HttpAsyncTest/tree/master/code/src/com/util/http
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。