OkHttp 的詳細介紹

隨着 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 源碼 。
轉載自:菜鳥窩

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章