OkHttp 的详细介绍

来源:互联网 发布:usb电流检测软件 编辑:程序博客网 时间:2024/06/03 14:58

随着 Android 版本和性能的不断更新和增强,网络请求的方法也在不断变化着,从 HttpURLConnetion 到 Apache Http Client,再到之前热门的 Volley,最后到现在的 OkHttp,网络请求的方法变得越来越简单化和方便化了,而在这篇文章所要介绍的就是目前最新也是最为热门的网络请求开源框架 —— OkHttp。
OkHttp 的详细介绍

1. OkHttp 是什么

Android为我们提供了两种HTTP交互的方式: HttpURLConnection 和 Apache HTTP Client,虽然两者都支持HTTPS,流的上传和下载,配置超时,IPv6和连接池,已足够满足我们各种HTTP请求的需求。但更高效的使用HTTP可以让您的应用运行更快、更节省流量。而OkHttp库就是为此而生。OKHttp 的基本定义是一款开源的网络请求的轻量级框架,由 Square 公司所贡献,该公司还贡献了一款很热门的开源框架,就是大家所熟知的图片加载框架 Picasso。

2. OkHttp 的优势

  1. 支持 SPDY ,共享同一个 Socket 来处理同一个服务器的所有请求。
  2. 如果 SPDY 不可用,则通过连接池来减少请求延时。
  3. 无缝的支持GZIP来减少数据流量。
  4. 缓存响应数据来减少重复的网络请求。
  5. OkHttp 会从很多常用的连接问题中自动恢复。如果您的服务器配置了多个 IP 地址,当第一个 IP 连接失败的时候,会自动尝试下一个IP。OkHttp还处理了代理服务器问题和SSL握手失败问题。
  6. 使用 OkHttp 无需重写您程序中的网络代码。OkHttp 实现了几乎和 java.net.HttpURLConnection 一样的 API。如果您用了 Apache HttpClient,则 OkHtt p也提供了一个对应的 okhttp-apache 模块。

OkHttp 的使用方法

网路请求中有 get 和 post 两种方法, OkHttp 作为网络请求框架,要了解 OkHttp 的使用方法,就是要了解如何使用 OKHttp 的 get 和 post 方法来请求和获取网络数据了。

1. Http get 方法

在了解 OkHtttp 的 get 使用方法之前,先来了解几个相关的类,如下所示。

OkHttpClient //客户端对象Request //OkHttp 中访问的请求Builder //辅助类Response //OkHttp 中的响应

了解了这些基本的相关类,掌握了如何使用这些类,就清楚了任何使用 get 方法了,使用的方法看如下代码。

OkHttpClient 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();}

可以明显看出,get 方法很简单,所以说 OkHttp 的网络请求方法很简单,只要几行代码就可以搞定了。

2. Http post 方法(JSON)

get 方法十分简单,post 方法也不复杂的,框架的使用都很方便,这里也有几个相应的类需要了解下。

MediaType // 数据类型RequestBody //请求数据

在 post 的方法中需要新增上面两个类,主要是因为 post 方法需要另外传递参数,在使用的时候,将所需要传递的参数写在 RequestBody 中就好了。具体的使用方法看代码了。

public 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();}

3. Http post 方法(FormData)

因为使用 post 方法时,传递 Json 对象参数和传递 FormData 有所不同,所以也特别介绍下。这里需要新了解一个类就可以了。

FormBody //表单数据类

使用方法和传递 JSON 对象参数有所不同,主要是要新构建一个表单数据构造器。

OkHttpClient client = new OkHttpClient();String post(String url, String json) throws IOException {  RequestBody body = new FormBody.Builder()                .add("type","1")                .build();  Request request = new Request.Builder()      .url(url)      .post(body)      .build();  Response response = client.newCall(request).execute();  return response.body().string();}

OkHttp 实现商城轮播广告

在文章《商城项目实战 | 3.1 AndroidImageSlider 实现炫酷轮播广告》中已经详细讲解了如何使用 AndroidImageSlider 实现炫酷的轮播广告,但是当时使用的数据都是写死的,也就是自己写的一些测试数据了,现在我们要从网络中获取网络数据,然后显示在我们的轮播广告中,这就要使用到网络请求开源框架 OkHttp 了。

1. gradle 添加依赖

在使用第三方框架的第一步都是要先在 build 中添加依赖的配置,使用 OkHttp 也是一样的。

dependencies {    compile fileTree(include: ['*.jar'], dir: 'libs')    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {        exclude group: 'com.android.support', module: 'support-annotations'    })    compile 'com.android.support:appcompat-v7:25.2.0'    compile 'com.android.support.constraint:constraint-layout:1.0.1'    testCompile 'junit:junit:4.12'    compile 'com.daimajia.slider:library:1.1.5@aar'    compile 'com.squareup.picasso:picasso:2.5.2'    compile 'com.nineoldandroids:library:2.4.0'    compile 'com.android.support:support-v4:25.2.0'    compile 'com.android.support:cardview-v7:25.2.0'    compile 'com.squareup.okhttp3:okhttp:3.6.0'    compile 'com.google.code.gson:gson:2.8.0'}

这里需要导入的依赖只有 OkHttp 和 Gson 了,其他的依赖都是之前实现炫酷的轮播广告时导入的。

2. 添加权限

在进行网络请求时,一定要记得添加一项权限,那就是网络请求权限,这是必不可少的。

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

3. 获取并且加载网络数据

已经导入好了 OkHttp,也加好了权限,下面就可以请求数据了,数据类型为 Json 格式,需要定义实体类,然后对获取的数据进行 Json 转换,首先定义实体类 BannerInfo。

public class BannerInfo {    private String name;//名称    private String imgUrl;//图片URL    private  String id;//描述    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getImgUrl() {        return imgUrl;    }    public void setImgUrl(String imgUrl) {        this.imgUrl = imgUrl;    }    public String getId() {        return id;    }    public void setId(String id) {        this.id = id;    }}

下面就是添加网络数据请求的操作了。
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case INIT_SLIDER_TYPE:
initSlider();
break;
}
}
};

private void getBannerData() {    String url ="http://112.124.22.238:8081/course_api/banner/query?type=1";        OkHttpClient client = new OkHttpClient();        Request request = new Request.Builder()                .url(url)                .build();        Call call = client.newCall(request);        call.enqueue(new Callback() {            @Override            public void onFailure(Call call, IOException e) {                Toast.makeText(getActivity(),e.getMessage().toString(),Toast.LENGTH_SHORT).show();            }            @Override            public void onResponse(Call call, Response response) throws IOException {                if(response.isSuccessful()){                    Type type = new TypeToken<List<BannerInfo>>(){}.getType();                    Gson gson = new Gson();                    List<BannerInfo> list= gson.fromJson(response.body().string(),type);                    for (BannerInfo bannerInfo:list)                    {                        listBanner.add(bannerInfo);                    }                    handler.sendEmptyMessage(INIT_SLIDER_TYPE);                }else {                    Toast.makeText(getActivity(),"IOException",Toast.LENGTH_SHORT).show();                }            }        });}

其中的 initSlider() 方法就是文章《商城项目实战 | 3.1 AndroidImageSlider 实现炫酷轮播广告》的实例中的配置 SliderLayout 的相关属性了,添加自定义的 Indicator,设置动画效果,添加图片列表数据以及设置监听事件了。

4. 效果图

运行代码,获取最终效果图。

OkHttp 更多的用法可以参考 Github 源码 。
转载自:菜鸟窝

0 0
原创粉丝点击