开源框架01(ion,Volley,retrofit;Glide,picasso,fresco)
来源:互联网 发布:箱体捉妖指标公式源码 编辑:程序博客网 时间:2024/05/23 11:33
1.开源框架合集
1.1网络请求
Android原生 HttpURLConnection,HttpClient
第三方的类库,XUtils,OKHttp,Afinal,Ion,Retrofit,Volley自己封装Socket实现,
请求的执行一般通过线程池来管理,异步请求得到的结果,通过接口回调,用Handler.post去主线程执行
//线程池的作用://1.可以维护线程数量的上限,节省系统资源//2.可以重用闲置的线程ExecutorService service = Executors.newFixedThreadPool(3);service.execute(new Runnable() { @Override public void run() { }});
1.2网络加载 Ion
依赖库: dependencies { compile 'com.koushikdutta.ion:ion:2.+'}可以加载图片 包括GIF链式编程Fluent自动取消请求,当Activity /finish();时支持HTTP/2,SPDY;HTTP/2(请求头少);SPDY(谷歌),支持缓存,Gzip压缩/** * ionDownload下载文件 */private void ionDownload() { //图片的路径 String url = URLContent.IMAGE; final File file = new File(Environment.getExternalStorageDirectory(), "ba.jpg"); //获取单例对象 Ion.with(this) .load(url) .write(file)//写入文件 .setCallback(new FutureCallback<File>() { @Override public void onCompleted(Exception e, File result) { if (e == null) { tv.setText(file.getAbsolutePath()); } else { tv.setText(e.getMessage()); } } });}/** * ionUploadMulti批量上传文件 */private void ionUploadMulti() { String url = URLContent.UPLOAD_MULTI; File file = new File(Environment.getExternalStorageDirectory(), "a.jpg"); File afile = new File(Environment.getExternalStorageDirectory() + "/Download/", "c.jpg"); //获取单例对象 Ion.with(this) .load(url) .setMultipartFile("file", file)//设置要上传的文件 //.setMultipartFile("file", afile)//设置要上传的文件 .asString() .setCallback(new FutureCallback<String>() { @Override public void onCompleted(Exception e, String result) { if (e == null) { tv.setText(result); } else { tv.setText(e.getMessage()); } } });}/** * ionUpload上传文件 */private void ionUpload() { String url = URLContent.UPLOAD; File file = new File(Environment.getExternalStorageDirectory() + "/Download/", "a.jpg"); //获取单例对象 Ion.with(this) .load(url) .setMultipartFile("file", file)//设置要上传的文件 .asString() .setCallback(new FutureCallback<String>() { @Override public void onCompleted(Exception e, String result) { if (e == null) { tv.setText(result); } else { tv.setText(e.getMessage()); } } });}/** * ionPOST请求 */private void ionPOST() { String url = URLContent.LOGIN; //获取单例对象 Ion.with(this) .load(AsyncHttpPost.METHOD, url) //设置请求体参数 .setBodyParameter("username", "hanhua") .setBodyParameter("password", "123456") .as(User.class) .setCallback(new FutureCallback<User>() { @Override public void onCompleted(Exception e, User result) { if (e == null) { tv.setText(result.toString()); } else { tv.setText("失败"); } } });}/** * ionGET请求 */public void ionGET() { String url = URLContent.TEST; //获取单例对象 Ion.with(this) .load(url)//设置请求的url .asString()//期望期望解析的数据类型 .setCallback(new FutureCallback<String>() { @Override public void onCompleted(Exception e, String result) { if (e == null) { tv.setText(result); } else { tv.setText(e.getMessage()); } } });}
1.3网络加载 Volley
2.3之后使用HttpURLConnection,2.3之前使用HttpClient支持取消请求有网络请求和图片加载,不支持下载文件依赖库:compile 'com.android.volley:volley:1.0.0'
/** * volleyPOST请求 */private void volleyPOST() { String url = URLContent.LOGIN; //创建请求队列 RequestQueue requestQueue = Volley.newRequestQueue(this); //创建请求对象 PostRequest request = new PostRequest(Request.Method.POST,url, new Response.Listener<String>() { @Override public void onResponse(String response) { //获取成功 } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { //获取失败 } }); //设置请求体的参数 写一个类继承StringRequest,重写getParams(),在增加一个addParams; request.addParams("name","haha"); //执行请求 requestQueue.add(request);}
//设置请求体的参数 写一个类继承StringRequest,重写getParams(),在增加一个addParams;public class PostRequest extends StringRequest { private Map<String, String> map; public PostRequest(int method, String url, Response.Listener<String> listener, Response.ErrorListener errorListener) { super(method, url, listener, errorListener); map = new HashMap<>(); } public PostRequest(String url, Response.Listener<String> listener, Response.ErrorListener errorListener) { this(0, url, listener, errorListener); } @Override protected Map<String, String> getParams() throws AuthFailureError { return map; } public void addParams(String s,String y){ map.put(s,y); }}
/** * volleyGET请求 */private void volleyGET() { String url = URLContent.TEST; //创建请求队列 RequestQueue requestQueue = Volley.newRequestQueue(this); //创建请求对象 StringRequest request = new StringRequest(url, new Response.Listener<String>() { @Override public void onResponse(String response) { //获取成功 } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { //获取失败 } }); //执行请求 requestQueue.add(request);}
1.4网络加载retrofit
依赖库:compile 'com.squareup.retrofit2:retrofit:2.1.0'还需配置gson解析库compile 'com.squareup.retrofit2:converter-gson:2.1.0'Gson: com.squareup.retrofit2:converter-gsonJackson: com.squareup.retrofit2:converter-jacksonMoshi: com.squareup.retrofit2:converter-moshiProtobuf: com.squareup.retrofit2:converter-protobufWire: com.squareup.retrofit2:converter-wireSimple XML: com.squareup.retrofit2:converter-simplexmlScalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars
8种请求:PUT DELETE POST GET
注解:@GET,@POST,@Path,@Field,@FormUrlEncoded,@Query,@QueryMap@Part,@PartMap,@Headers
tomcat版本是8.0.33能下载到图片
请求数据
@OnClick(R.id.bt)public void onClick() { //retrofitGET(); //retrofitPost(); //retrofitupload(); download();}/** * 下载图片 */private void download() { Call<ResponseBody> image = heiMiApi.getImage(); image.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { ResponseBody body = response.body(); Bitmap bitmap = BitmapFactory.decodeStream(body.byteStream()); tv.setBackground(new BitmapDrawable(bitmap)); } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { } });}/** * 上传图片 *///传图片固定的模式final String FILE_PART = "file\"; filename=\"";private void retrofitupload() { HashMap<String, RequestBody> map = new HashMap<>(); File file = new File(Environment.getExternalStorageDirectory() + "/Download/", "a.jpg"); //获取RequestBody RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpeg"), file); map.put(FILE_PART+file.getName(),requestBody); Call<Result> resultCall = heiMiApi.upMulitload(map); resultCall.enqueue(new Callback<Result>() { @Override public void onResponse(Call<Result> call, Response<Result> response) { Result body = response.body(); tv.setText(body.msg); } @Override public void onFailure(Call<Result> call, Throwable t) { } });}/** * post请求 */private void retrofitPost() { //得到请求的封装对象,此时请求还没有执行。这个请求中封装了url和参数 //以及你期望解析的类型 Call<User> login = heiMiApi.login("username", "password"); //执行请求 同步请求 //productList.execute(); login.enqueue(new Callback<User>() { @Override public void onResponse(Call<User> call, Response<User> response) { User body = response.body(); tv.setText(body.toString()); } @Override public void onFailure(Call<User> call, Throwable t) { tv.setText("失败"); } });}/** * get请求 */private void retrofitGET() { //得到请求的封装对象,此时请求还没有执行。这个请求中封装了url和参数 //以及你期望解析的类型 Call<Stu> productList = heiMiApi.getProductList(); //执行请求 同步请求 会阻塞UI,不推荐 //productList.execute(); productList.enqueue(new Callback<Stu>() { @Override public void onResponse(Call<Stu> call, Response<Stu> response) { Stu body = response.body(); tv.setText(body.toString()); } @Override public void onFailure(Call<Stu> call, Throwable t) { tv.setText("失败"); } });}private HeiMiApi getRetrofit() { String url = URLContent.SERVER_HOST; //创建Retrofit实例对象 Retrofit retrofit = new Retrofit.Builder() //设置服务器解析地址,要求url必须以'/'结束 .baseUrl(url) //使用Gson作为Json数据的转换 .addConverterFactory(GsonConverterFactory.create()) .build(); //创建接口的实现类对象,让Retrofit创建一个实例对象 //内部通过动态代理来创建实例对象,并且监听对象方法的调用 //当我们调用业务方法是,Retrofit内部就会获取方法的注解信息 //这些信息包含请求的方式 url和请求参数,于是它会自动利用OKHttp发送这些请求 return retrofit.create(HeiMiApi.class);}
创建一个类存放请求的路径和参数,请求方式
/** * Created by yin13 on 2016/12/28. */public interface HeiMiApi { //定义业务方法,指定url路径和参数 @GET("test") Call<Stu> getProductList(); //path注解可以替换某一段动态多变的路径 @GET("test/{category}/{page}") Call<Stu> getProducts(@Path("category") String category, @Path("page") int page); //拼接批量查询参数 search?key=word&sort=1&...... @GET("search") Call<Stu> searchProducts(@QueryMap HashMap<String, String> map); //自定义header参数 @Headers({ "Accept: application/vnd.github.v3.full+json", "User-Agent:Retrofit-Sample-App", "location:BJ,China" }) @GET("search") Call<Stu> searchProductsl(@QueryMap HashMap<String, String> map); //定义登陆的方法,并通过@Field注释配置请求体参数 @FormUrlEncoded//对请求体的数据进行url编码 @POST("login") Call<User> login(@Field("username") String param1, @Field("password") String param2); //如果要以二进制的方式接收结果,那么类型就是ResponseBody @GET("image") Call<ResponseBody> getImage(); //上传头像业务方法 @Multipart //以多块的格式上传文件 @POST("upload") Call<Result> upload(@Part("file\"; filename=\"") RequestBody reqbody); //批量上传业务方法 @Multipart //以多块的格式上传文件 @POST("uploadMulti") Call<Result> upMulitload(@PartMap HashMap<String, RequestBody> map);}
还需创建一些javabean
2.图片加载Glide
网址:https://github.com/bumptech/glide
// 使用Glide加载图片Glide.with(holder.image.getContext()) .load(Constants.IMAGES[position]) .centerCrop()//设置从中间剪切 .placeholder(R.mipmap.ic_launcher)//设置默认图片 .error(R.mipmap.error)//设置error失败的图片 .crossFade(1000)//渐变的时间 .into(holder.image);//要设置的imageview
3.图片加载Picasso
网址:https://github.com/square/picasso
//使用Picasso加载图片Picasso.with(holder.image.getContext()) .load(Constants.IMAGES[position]) .placeholder(R.mipmap.ic_launcher) .error(R.mipmap.error) .centerCrop() .noFade()//设置不需要渐渐显示的动画效果 .resize(400,400)//指定压缩参考的宽高比 .into(holder.image);
4.图片加载Fresco
网址:https://github.com/facebook/fresco
支持WebPs比JPEG质量更高,比jpg体积小40%
在Application初始化Fresco 必须初始化
public class App extends Application { @Override public void onCreate() { super.onCreate(); //初始化Fresco Fresco.initialize(this); }}
布局中写:
<com.facebook.drawee.view.SimpleDraweeView android:clickable="true" xmlns:fresco="http://schemas.android.com/apk/res-auto" fresco:fadeDuration="1000" fresco:actualImageScaleType="centerCrop" fresco:placeholderImage="@mipmap/ic_launcher" fresco:placeholderImageScaleType="centerCrop" fresco:failureImage="@mipmap/error" fresco:roundAsCircle="true" fresco:roundingBorderWidth="4dp" fresco:roundingBorderColor="#0000ff" android:layout_gravity="center" android:id="@+id/tv_sdv" android:layout_width="200dp" android:layout_height="200dp" />
Android应用程序的入口函数,onCreate();
0 0
- 开源框架01(ion,Volley,retrofit;Glide,picasso,fresco)
- 网络请求库(ion、volley、retrofit)和图片加载库(glide、picasso、fresco)
- Android图片加载框架:ImageLoader,Volley,Picasso,Glide,Fresco
- Android图片加载框架:ImageLoader,Volley,Picasso,Glide,Fresco
- Android图片框架对比Universal-Image-Loader,android-Volley,Picasso、Fresco和Glide五大Android开源组件加载网络图片的优缺点比较
- Android图片框架对比Universal-Image-Loader,android-Volley,Picasso、Fresco和Glide五大Android开源组件加载网络图片的优缺点比较
- 常用的图片处理框架UIL、Picasso、Glide、Fresco、Volley ImageLoader比较分析
- 图片加载框架Glide,Picasso fresco volley imageloader Universal Image Loader的比较
- Android图片加载与缓存开源框架总结七部曲:Glide Picasso ImageLoader Fresco ASimpleCache等
- Universal-Image-Loader,android-Volley,Picasso、Fresco和Glide五大Android开源组件加载网络图片比较
- Universal-Image-Loader,android-Volley,Picasso、Fresco和Glide五大Android开源组件加载网络图片比较
- Universal-Image-Loader,android-Volley,Picasso、Fresco和Glide五大Android开源组件加载网络图片比较
- Universal-Image-Loader,android-Volley,Picasso、Fresco和Glide五大Android开源组件加载网络图片比较
- Universal-Image-Loader,android-Volley,Picasso、Fresco和Glide五大Android开源组件加载网络图片比较
- Universal-Image-Loader,android-Volley,Picasso、Fresco和Glide五大Android开源组件加载网络图片比较
- Glide、Picasso和Fresco
- Glide、Picasso和Fresco
- Picasso,Glide,Fresco 对比
- PHP中$GLOBALS与global的区别
- 学习、工作心得分享
- 39,40,216 Combination Sum I II III
- ServletContext详解
- MYSQL经典SQL之生日问题
- 开源框架01(ion,Volley,retrofit;Glide,picasso,fresco)
- PAT-1009B 说反话 (20)
- 单向链表
- VBScript读取注册表中REG_MULTI_SZ类型数值的两种方法
- 说说UINavigationController那些事儿(下)
- Kotlin写Android(一)——项目创建
- 关于No mapping found for HTTP request with URI
- WordPress发送注册用户设置密码邮件提示:您的密码重设链接无效,请在下方请求新链接
- 关于图片或者文件在数据库的存储方式归纳