上篇中叙述了Afinal的finalDB和finalActivity的用法,接下来讲FinalHttp和FinalBitmap。
FinalHttp的使用方法:
FinalHttp 对 HttpClient再次封装,最简洁的就是增加了许多回调的方法,对Get 和 Post 请求进行了简化。此外还有put,delete和download方法。另外一点就是FinalHttp加入线程池操作,默认的Http请求池连接为3。下面是为FinalHttp可配置的操作.
FinalHttp finalHttp = new FinalHttp(); finalHttp.addHeader("Accept-Charset", "UTF-8");//配置http请求头 finalHttp.configCharset("UTF-8"); finalHttp.configCookieStore(null); finalHttp.configRequestExecutionRetryCount(3);//请求错误重试次数 finalHttp.configSSLSocketFactory(null); finalHttp.configTimeout(5000);//超时时间 finalHttp.configUserAgent("Mozilla/5.0");//配置客户端信息
源码中的get请求:
// ------------------get 请求----------------------- public void get(String url, AjaxCallBack extends Object> callBack) { get(url, null, callBack); } public void get(String url, AjaxParams params, AjaxCallBack extends Object> callBack) { sendRequest(httpClient, httpContext, new HttpGet(getUrlWithQueryString(url, params)), null, callBack); } public void get(String url, Header[] headers, AjaxParams params, AjaxCallBack extends Object> callBack) { HttpUriRequest request = new HttpGet(getUrlWithQueryString(url, params)); if (headers != null) request.setHeaders(headers); sendRequest(httpClient, httpContext, request, null, callBack); }
上述有三个get方法,不同之处在于参数的不同,先看最简单的get方法使用:
FinalHttp fh = new FinalHttp(); fh.get("http://www.yangfuhai.com", new AjaxCallBack(){ @Override public void onLoading(long count, long current) { //每1秒钟自动被回调一次 textView.setText(current+"/"+count); } @Override public void onSuccess(String t) { textView.setText(t==null?"null":t); } @Override public void onStart() { //开始http请求的时候回调 } @Override public void onFailure(Throwable t, String strMsg) { //加载失败的时候回调 } });
上述get方法中有两个参数,一为访问的路径,一个为回调函数,请求后的相应操作可以在回调函数中处理。
源码中的post请求:
// ------------------post 请求----------------------- public void post(String url, AjaxCallBack extends Object> callBack) { post(url, null, callBack); } public void post(String url, AjaxParams params, AjaxCallBack extends Object> callBack) { post(url, paramsToEntity(params), null, callBack); } public void post(String url, HttpEntity entity, String contentType, AjaxCallBack extends Object> callBack) { sendRequest(httpClient, httpContext, addEntityToRequestBase(new HttpPost(url), entity), contentType, callBack); } publicvoid post(String url, Header[] headers, AjaxParams params, String contentType, AjaxCallBack callBack) { HttpEntityEnclosingRequestBase request = new HttpPost(url); if (params != null) request.setEntity(paramsToEntity(params)); if (headers != null) request.setHeaders(headers); sendRequest(httpClient, httpContext, request, contentType, callBack); } public void post(String url, Header[] headers, HttpEntity entity, String contentType, AjaxCallBack extends Object> callBack) { HttpEntityEnclosingRequestBase request = addEntityToRequestBase( new HttpPost(url), entity); if (headers != null) request.setHeaders(headers); sendRequest(httpClient, httpContext, request, contentType, callBack); }
同get方法一样,不同之处也在于参数。简单post方法应用:
AjaxParams params = new AjaxParams(); params.put("username", "michael yang"); params.put("password", "123456"); params.put("email", "[email protected]"); params.put("profile_picture", new File("/mnt/sdcard/pic.jpg")); // 上传文件 params.put("profile_picture2", inputStream); // 上传数据流 params.put("profile_picture3", new ByteArrayInputStream(bytes)); // 提交字节流 FinalHttp fh = new FinalHttp(); fh.post("http://www.yangfuhai.com", params, new AjaxCallBack(){ @Override public void onLoading(long count, long current) { textView.setText(current+"/"+count); } @Override public void onSuccess(String t) { textView.setText(t==null?"null":t); } });
这就是ainalhttp的get和post方法的应用,此外使用比较多的一个方法是download。
来看download的源码:
// ---------------------下载--------------------------------------- public HttpHandlerdownload(String url, String target, AjaxCallBack callback) { return download(url, null, target, false, callback); } public HttpHandler download(String url, String target, boolean isResume, AjaxCallBack callback) { return download(url, null, target, isResume, callback); } public HttpHandler download(String url, AjaxParams params, String target, AjaxCallBack callback) { return download(url, params, target, false, callback); } public HttpHandler download(String url, AjaxParams params, String target, boolean isResume, AjaxCallBack callback) { final HttpGet get = new HttpGet(getUrlWithQueryString(url, params)); HttpHandler handler = new HttpHandler (httpClient, httpContext, callback, charset); handler.executeOnExecutor(executor, get, target, isResume); return handler; }
download的简单应用:
FinalHttp fh = new FinalHttp(); //调用download方法开始下载 HttpHandler handler = fh.download("http://www.xxx.com/下载路径/xxx.apk", //这里是下载的路径 true,//true:断点续传 false:不断点续传(全新下载) "/mnt/sdcard/testapk.apk", //这是保存到本地的路径 new AjaxCallBack() { @Override public void onLoading(long count, long current) { textView.setText("下载进度:"+current+"/"+count); } @Override public void onSuccess(File t) { textView.setText(t==null?"null":t.getAbsoluteFile().toString()); } }); //调用stop()方法停止下载 handler.stop();
FinalBitmap的使用:
private static FinalBitmap mFinalBitmap; // //////////////////////// config method // start//////////////////////////////////// private FinalBitmap(Context context) { mContext = context; mConfig = new FinalBitmapConfig(context); configDiskCachePath(Utils.getDiskCacheDir(context, "afinalCache") .getAbsolutePath());// 配置缓存路径 configDisplayer(new SimpleDisplayer());// 配置显示器 configDownlader(new SimpleDownloader());// 配置下载器 }
以上为FinalBitmap的构造器源码,代码详细信息已经注释,我们可以看出,FinalBitmap使用的是线程安全的单例模式,因此,当我们想获取一个FinalBitmap对象的时候,我们可以这样做:
FinalBitmap finalBitmap = FinalBitmap.create(context);
之后可以自己去配置相关的参数:
finalBitmap.configBitmapLoadThreadSize(3); //图片大小 finalBitmap.configBitmapMaxHeight(800); finalBitmap.configBitmapMaxWidth(480); //磁盘缓存路径 finalBitmap.configDiskCachePath(""); finalBitmap.configDiskCacheSize(10*1024); //配置显示 finalBitmap.configDisplayer(new Displayer() { @Override public void loadFailDisplay(View imageView, Bitmap bitmap) { // TODO Auto-generated method stub //设置失败 显示图片 404 等等 } @Override public void loadCompletedisplay(View imageView, Bitmap bitmap, BitmapDisplayConfig config) { // TODO Auto-generated method stub // 加载成功 开启动画等等imageView.startAnimation(); } }); //可自己定义下载器 finalBitmap.configDownlader(new Downloader() { @Override public byte[] download(String urlString) { // TODO Auto-generated method stub //自己写下载代码。这个已经是异步操作了 return null; } }); //加载时显示的图片。即默认图片 finalBitmap.configLoadingImage(null); //配置内存缓存大小 finalBitmap.configMemoryCacheSize(4); //待我后面再讲 finalBitmap.configRecycleImmediately(true); finalBitmap.setExitTasksEarly(true);
finalBitmap提供了display方法供大家调用,源码中一共有六个不同参数的dispaly方法。(大家可以去看源码)。
下面展示一种加载网络图片的display的使用方法:
private GridView gridView; private FinalBitmap fb; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.images); gridView = (GridView) findViewById(R.id.gridView); gridView.setAdapter(mAdapter); fb = FinalBitmap.create(this);//初始化FinalBitmap模块 fb.configLoadingImage(R.drawable.downloading); //这里可以进行其他十几项的配置,也可以不用配置,配置之后必须调用init()函数,才生效 //fb.configBitmapLoadThreadSize(int size) //fb.configBitmapMaxHeight(bitmapHeight) } ///////////////////////////adapter getView//////////////////////////////////////////// public View getView(int position, View convertView, ViewGroup parent) { ImageView iv; if(convertView == null){ convertView = View.inflate(BitmapCacheActivity.this,R.layout.image_item, null); iv = (ImageView) convertView.findViewById(R.id.imageView); iv.setScaleType(ScaleType.CENTER_CROP); convertView.setTag(iv); }else{ iv = (ImageView) convertView.getTag(); } //bitmap加载就这一行代码,display还有其他重载,详情查看源码 fb.display(iv,Images.imageUrls[position]);