Android网络开源框架

来源:互联网 发布:淘宝店铺估价 编辑:程序博客网 时间:2024/05/27 02:30

说起网络通信开源框架,目前有很多,Android系统为开发者提供了两种HTTP交互方式HttpURLConnection和ApacheHttpClient,两者都支持Https,流上传和下载,超时设置,IPV6及其连接池,但是为了更高效的使用Http,okhttp开源库为此诞生,就从最开始的okhttp讲起吧!

okhttp

一个处理网络请求的开源项目,移动支付Square公司开发的轻量级框架

Source Code on Github

优点:

  • 支持HTTP/2和SPDY(Google开发的基于TCP传输层协议,用以最小化网络延迟,提升网络速度,优化用户的网络使用体验),对同一台主机的所有请求共享同一个socket.

  • 当SPDY不可用时,使用连接池减少请求的延迟。

  • 透明的GZIP压缩减少下载数据大小。

  • 缓存响应避免重复的网路请求。

Okhttp在网络不好的情况下,它能够避免常见网络连接问题。如果HTTP服务有多个IP地址,第一次连接失败,会尝试其他可选的地址,而对于IPV4+IPV6及其托管在冗余数据中心的服务是不错的选择,使用最新TLS特性(SNI{(Server Name Indication)是为了解决一个服务器使用多个域名和证书的SSL/TLS扩展。}和ALPN(应用层协议谈判,是一个TLS扩展))初始化 HTTP 连接,当握手失败时,会降级使用TSL1.0初始化连接。

> Get A URLOkHttpClient client = new OkHttpClient();String run(String url) throws IOException {    Request request = new Request.Builder()      .url(url)      .build();    Response response = client.newCall(request).execute();    return response.body().string();}
> POST TO A SERVERpublic static final MediaType JSON    = MediaType.parse("application/json; charset=utf-8");OkHttpClient client = new OkHttpClient();String post(String url, String json) throws IOException {    RequestBody body = RequestBody.create(JSON, json);    Request request = new Request.Builder()      .url(url)      .post(body)      .build();    Response response = client.newCall(request).execute();    return response.body().string();}

Okhttp依赖Okio库,okio作为java.nio、java.io的补充类库,方便快速访问存储和处理数据。

JAR download

引入到项目中

MAVEN

<dependency>                  <groupId>com.squareup.okhttp3</groupId>  <artifactId>okhttp</artifactId>  <version>(insert latest version)</version></dependency>

Gradle

compile 'com.squareup.okhttp3:okhttp:(insert latest version)'

Retrofit

并不是一个完整的网络请求库,而是将REST API转换成Java接口的开源库。请求API的接口遵循REST规范,基于注解使得代码简洁,默认JSON解析器是使用GSON,Okhttp实现网络请求。

其实此库是基于android-async-http、HttpURIConnection、ApacheHttpClient和OkHttp的二次封装开发的

Source Code on Github

官方源码提供了大概有42个文件,25个HTTP相关文件,实际使用起来很方便。

官方介绍使用如下:

1.将你的HTTP 的API转成java接口

public interface GitHubService {    @GET("index")    Call<ResponseBodyBean> getIndex();}

2.创建Retrofit对象

Retrofit retrofit = new Retrofit.Builder()        .baseUrl("http://localhost:8080/")        .build();GitHubService service = retrofit.create(GitHubService.class);
  • 注:此处Retrofit2的baseUri是以/(斜线)结尾的,不然会报IllegalArgumentException错。

  • 注:GitHubService是interface,而不是class,所以没办法直接调用,所以需要一个代理对象GitHubService

3.接口调用(异步请求)

Call<ResponseBody> call = service .getIndex("user");//回调方法执行在主线程住call.enqueue(new Callback<ResponseBodyBean>() {    @Override    public void onResponse(Call<ResponseBodyBean> call,        Response<ResponseBodyBean> response) {        try {            //获取到解析后的数据            Log.e("TAG", response.body().string());        } catch (IOException e) {            e.printStackTrace();        }    }    //请求失败回调    @Override    public void onFailure(Call<ResponseBodyBean> call,             Throwable t) {        //打印异常任务栈        Log.e("TAG", t.printStackTrace();)    }});

Picasso

实现图片下载及其二级缓存,日常的一些问题。

  • 在adapter中正常处理ImageView回收和下载的取消
  • 尽量小的内存实现复杂的图片变换

Source Code on Github

官方提供大概36个文件,内部使用LruCache算法进行二级缓存。

官方介绍使用如下:

实现图片下载并渲染到ImageView中

Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);

自定义的布局设置图片,target是指实现了Target接口的自定义View

Picasso.with(context).load(url).placeholder(R.drawable.tab_item_bg).into(target);

adapter中使用

@Override public void getView(int position,                     View convertView,                     ViewGroup parent) {     ImageView view = (ImageView) convertView;     if (view == null) {         view = new ImageView(context);     }     String url = getItem(position);     Picasso.with(context).load(url).into(view);}

自动设置图片宽高像素大小

Picasso    .with(context)     .load(url)     .resize(50, 50)     .centerCrop()     .into(imageView)

引入到项目中

Maven

<dependency>  <groupId>com.squareup.picasso</groupId>  <artifactId>picasso</artifactId>  <version>2.5.2</version></dependency>

Gradle

compile 'com.squareup.picasso:picasso:2.5.2'

square家的开源项目先说到这里,想要了解其他请查看:https://github.com/square ,写到这里呐,不得不说下与Picasso类似的,也是比较强大,Google推荐的并用于Android平台上的图片加载和缓存库,也是被广泛应用在google的开源项目中,相比大家也知道了,并且经常使用——Glide

Glide

快速高效的Android图片加载库,对包含图片的滚动列表做了流畅的优化。

  • 支持GIF格式的图片显示
  • 默认情况下还是使用HttpUrlConnection网络请求,但你也可以使用Volley或者Okhttp等开源库进行替换

Source Code on Github

官方介绍使用如下:

Glide.with(this)    .load(Url)    .into(imageView);

性能

Glide 充分考虑了Android图片加载性能的两个关键方面:

  • 图片解码速度

  • 解码图片带来的资源压力

Glide使用了多个步骤来确保在Android上加载图片尽可能的快速和平滑:

  • 自动、智能地下采样(downsampling)和缓存(caching),以最小化存储开销和解码次数;

  • 积极的资源重用,例如字节数组和Bitmap,以最小化昂贵的垃圾回收和堆碎片影响;

  • 深度的生命周期集成,以确保仅优先处理活跃的Fragment和Activity的请求,并有利于应用在必要时释放资源以避免在后台时被杀掉。

引入到项目中

Maven

<dependency> <groupId>com.github.bumptech.glide</groupId>  <artifactId>glide</artifactId>  <version>4.3.0</version>  <type>aar</type></dependency><dependency>  <groupId>com.google.android</groupId>  <artifactId>support-v4</artifactId>  <version>r7</version></dependency><dependency>  <groupId>com.github.bumptech.glide</groupId>  <artifactId>compiler</artifactId>  <version>4.3.0</version>  <optional>true</optional></dependency>

Gradle

repositories {  mavenCentral()  maven { url 'https://maven.google.com' }}dependencies {    compile 'com.github.bumptech.glide:glide:4.3.0'    annotationProcessor 'com.github.bumptech.glide:compiler:4.3.0'}
原创粉丝点击