okHttp 使用介紹

2016-02-05

error

okHttp 是 Square 推出的一套 Library,他提供我們快速的建立一個輕量化的 HttpClient,透過他的 GET.POST.PUT.DELETE.PATCH... 等方法來操作後端 api,目前 release 到 v3.0.1,類似的 Library 還有 Google 的 Volley




dependency 位址

compile 'com.squareup.okhttp3:okhttp:3.0.1'



以下示範 GET 與 POST 如何使用~

測試時記得在 Manifest 要加上網路權限

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



GET

        AsyncTask getTask = new AsyncTask() {
            @Override
            protected Object doInBackground(Object[] params) {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url("https://api.github.com/search/repositories?q=abcdefghijklmnopq")
                        .get()
                        .build();
                try {
                    Response response = client.newCall(request).execute();
                    System.out.println("狀態>>>"+response.code());
                    System.out.println("資料>>>"+response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        };
        getTask.execute();


POST

        AsyncTask postTask = new AsyncTask() {
            @Override
            protected Object doInBackground(Object[] params) {
                OkHttpClient client = new OkHttpClient();
                MediaType JSON = MediaType.parse("application/json; charset=utf-8");
                RequestBody body = RequestBody.create(JSON, "{\"Name\":\"anson\",\"Age\":18}");

                Request request = new Request.Builder()
                        .url(yourUrl)
                        .post(body)
                        .build();
                try {
                    Response response = client.newCall(request).execute();
                    System.out.println("狀態>>>"+response.code());
                    System.out.println("資料>>>"+response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        };
        postTask.execute();



有發現GET與POST的使用方法幾乎一模一樣嗎

只差在POST時需要給資料(RequestBody)而已~~

其他的PUT.DELETE.PATCH...以此類推

下面介紹一些常用到的設定




OkHttpClient 設定

使用 Builder 來操作

OkHttpClient.Builder builder = new OkHttpClient.Builder();

ex.1 調整 Timeout

Timeout 若不設定,預設為10秒

builder.connectTimeout(30, TimeUnit.SECONDS);
builder.readTimeout(15, TimeUnit.SECONDS);
builder.writeTimeout(20, TimeUnit.SECONDS);

ex.2 設定 Cache 儲存空間

final int CACHE_SIZE = 10 * 1024 * 1024;
builder.cache(new Cache(MainActivity.this.getExternalCacheDir(), CACHE_SIZE));

ex.3 設定 NetworkInterceptor

需要與 Cache 一起使用

                builder.addNetworkInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Response originalResponse = chain.proceed(chain.request());
                        if (true) {
                            int maxAge = 60; //有網路時..讀取快取1分鐘內資料
                            return originalResponse.newBuilder()
                                    .header("Cache-Control", "public, max-age=" + maxAge)
                                    .build();
                        } else {
                            int maxStale = 60 * 60 * 24 * 28;  //無網路時..讀取快取4周內資料
                            return originalResponse.newBuilder()
                                    .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                                    .build();
                        }
                    }
                });

最後建立 OkHttpClient 實體

OkHttpClient client = builder.build();



添加 Repuest Header

Request request = new Request.Builder()
    .url("URL")
    .addHeader("NAME_1","VALUE_1")
    .addHeader("NAME_2","VALUE_2")
    .addHeader("NAME_3","VALUE_3")
    .build();