OKHttp官方示例翻譯

package dh.okhttp_demo;

import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

import com.google.gson.Gson;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import okhttp3.Authenticator;
import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Credentials;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.Route;
import okio.BufferedSink;

/**
 * 這個項目主要列舉一下okhttp的常用用法
 * 主要依據(jù)okhttp在github上提供的官方教程
 * github教程地址:https://github.com/square/okhttp/wiki/Recipes
 * 在必要的地方寫好注釋,以便不時之需
 *
 * 包括:
 *
 * 同步get
 * 異步get
 * 獲取Headers
 * post一個字符串
 * post一個流
 * post一個文件
 * post表單參數(shù)
 * post多部分的請求
 * 結(jié)合GSON解析json數(shù)據(jù)
 * 響應緩存
 * 取消請求
 * timeout設置
 * 請求前配置
 * 處理身份驗證
 */


public class MainActivity extends AppCompatActivity
        implements View.OnClickListener{

    private static final String TAG_CONTENT = "OK_HTTP";

    private final OkHttpClient client = new OkHttpClient();
    private final Gson gson = new Gson();
    private final ScheduledExecutorService executor =
            Executors.newScheduledThreadPool(1);

    public static final MediaType MEDIA_TYPE_MARKDOWN
            = MediaType.parse("text/x-markdown; charset=utf-8");
    private static final String IMGUR_CLIENT_ID = "9199fdef135c122";
    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.synchronous_get).setOnClickListener(this);
        、、、其余的監(jiān)聽注冊一樣

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.synchronous_get: {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        SynchronousGet();
                    }
                }).start();
            }
            break;
            、、、
            //其余一樣方法調(diào)用寫法一樣,在4.0后強制規(guī)定不能在UI線程發(fā)起網(wǎng)絡請求
            break;
            default:break;
        }

    }

    /**
     * 同步get,最普通的,順序執(zhí)行
     *
     * 獲取response的headers,name,value
     * 獲取response的body信息
     * 其中response.body().toString()會把body信息一次性加載到內(nèi)存,
     * 所以這種方法只適合body大小小于1MB的
     */

    private void SynchronousGet() {
        Request request = new Request.Builder()
                .url("https://publicobject.com/helloworld.txt")
                .build();
        try {
            Response response = client.newCall(request).execute();
            Headers responseHeaders = response.headers();
            for (int i = 0; i < responseHeaders.size(); i++) {
                Log.d(TAG_CONTENT, responseHeaders.name(i) + ":"
                        + responseHeaders.value(i));
            }
            Log.d(TAG_CONTENT, response.body().toString());
            Log.d(TAG_CONTENT,"同步");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 異步get
     *
     * 使用OKHttpClient的enqueue方法實現(xiàn)異步回調(diào),另開一個線程下載文件,
     * 當response可讀時回調(diào)接口
     * 因為OKHttp沒有提供讀取response body時異步的API,
     * 回調(diào)完成后就回到了UI線程,所以解析response時可能阻塞UI線程
     */
    private void AsynchronousGet() {
        Log.d(TAG_CONTENT, "1");
        Request request = new Request.Builder()
                .url("https://publicobject.com/helloworld.txt")
                .build();
        /**
         * 匿名內(nèi)部類實現(xiàn)callback
         */
        Log.d(TAG_CONTENT, "2");
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG_CONTENT, "3");
                Headers responseHeaders = response.headers();
                for (int i = 0; i < responseHeaders.size(); i++) {
                    Log.d(TAG_CONTENT, responseHeaders.name(i) + ":"
                            + responseHeaders.value(i));
                }
                Log.d(TAG_CONTENT, response.body().toString());
                Log.d(TAG_CONTENT,"異步");
            }
        });
        Log.d(TAG_CONTENT, "4");
    }

    /**
     * 存取headers
     *
     * 一個典型的HTTP頭(HTTP headers)類似于Map<String, String>,一個字段一個值或者沒有值
     * 少數(shù)headers允許多個值,例如Vary,OkHttp's APIs兩者都能處理
     *
     * 發(fā)送請求時:
     * 使用header(name, value)方法添加請求頭(request headers),如果原來有該字段,
     * 那么直接覆蓋原來的,原來對應的值就會被新值替換
     * 使用addHeader(name, value)方法添加header,原來有沒有該字段沒有影響
     * 接收返回信息時:
     * 使用header(name)方法返回最新的name對應的值,如果沒有值,返回null
     * 使用headers(name)方法,以list的形式返回該字段對應的所有值。
     */
    private void AccessHeaders() {
        Request request = new Request.Builder()
                .url("https://api.github.com/repos/square/okhttp/issues")
                .header("User-Agent", "OkHttp Headers.java")
                .addHeader("Accept", "application/json; q=0.5")
                .addHeader("Accept", "application/vnd.github.v3+json")
                .build();
        try {
            Response response = client.newCall(request).execute();
            Log.d(TAG_CONTENT, "Server:" + response.header("Server"));
            Log.d(TAG_CONTENT, "Date:" + response.header("Date"));
            Log.d(TAG_CONTENT, "Vary:" + response.headers("Vary"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * post一個string
     * 指定postBody的類型為markdown,通過的post方法把postBody發(fā)送出去并轉(zhuǎn)換為html文件
     * 發(fā)送到web服務器
     * 因為postBody是整個加載到內(nèi)存中,所以大小不能超過1MB
     */
    private void PostString() {
        String postBody = ""
                + "Releases\n"
                + "--------\n"
                + "\n"
                + " * _1.0_ May 6, 2013\n"
                + " * _1.1_ June 15, 2013\n"
                + " * _1.2_ August 11, 2013\n";

        Request request = new Request.Builder()
                .url("https://api.github.com/markdown/raw")
                .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody))
                .build();

        try {
            Response response = client.newCall(request).execute();
            Log.d(TAG_CONTENT, response.body().toString());
        } catch (IOException e) {
            e.printStackTrace();
        }


    }


    /**
     * post一個流
     * 流以一個RequestBody對象的形式存在
     * RequestBody的內(nèi)容通過寫入的方式生成
     * 這里寫入是通過okio中BufferedSink的writeUtf8方法
     * 也可以用sdk的BufferedSink.outputStream()方法寫入
     */
    private void PostStreaming() {
        RequestBody requestBody = new RequestBody() {
            @Override
            public MediaType contentType() {
                return MEDIA_TYPE_MARKDOWN;
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                sink.writeUtf8("Number\n");
                sink.writeUtf8("---------\n");
                for (int i = 2; i <=997; i++) {
                    sink.writeUtf8(String.format(" * %s = %s\n", i, factor(i)));
                }
            }
            private String factor(int n) {
                for (int i = 2; i < n; i++) {
                    int x = n / i;
                    if (x * i == n) return factor(x) + " × " + i;
                }
                return Integer.toString(n);
            }
        };

        Request request = new Request.Builder()
                .url("https://api.github.com/markdown/raw")
                .post(requestBody)
                .build();

        try {
            Response response = client.newCall(request).execute();
            Log.d(TAG_CONTENT, response.body().toString());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * post一個文件
     * 使用文件作為RequestBody
     */
    private void PostFile() {
        File file = new File(Environment.getExternalStorageDirectory(), "README.md");

        Request request = new Request.Builder()
                .url("https://api.github.com/markdown/raw")
                .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
                .build();

        try {
            Response response = client.newCall(request).execute();
            Log.d(TAG_CONTENT, response.body().toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * post表單元素
     * 通過FormBody.Builder()方法創(chuàng)建一個類似于HTML<form>形式的RequestBody
     * 鍵值對將使用HTML兼容的URL編碼形式進行編碼
     */
    private void PostForm() {
        RequestBody formBody = new FormBody.Builder()
                .add("search", "Jurassic Park")
                .build();

        Request request = new Request.Builder()
                .url("https://en.wikipedia.org/w/index.php")
                .post(formBody)
                .build();

        try {
            Response response = client.newCall(request).execute();
            Log.d(TAG_CONTENT, response.body().toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * post分塊請求
     * 使用MultipartBody.Builder()構(gòu)建包含多個塊的RequestBody,并且兼容HTML文件上傳表單
     * 每個塊本身也是一個request body,也能定義自己的headers
     * 這些headers描述一個塊,例如Content-Disposition,如果需要,
     * content-Length and Content-Type這些headers會被自動添加
     */
    private void PostMultipart() {

        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("title", "Square logo")
                .addFormDataPart("image", "logo-square.png",
                        RequestBody.create(MEDIA_TYPE_PNG,
                                new File(Environment.getExternalStorageDirectory(),
                                        "logo-square.png")))
                .build();

        Request request = new Request.Builder()
                .header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
                .url("https://api.imgur.com/3/image")
                .post(requestBody)
                .build();

        try {
            Response response = client.newCall(request).execute();
            Log.d(TAG_CONTENT, response.body().toString());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 配合GSON解析json
     * ResponseBody.charStream()方法使用響應頭Content-Type去指定選擇哪個字符集解碼json數(shù)據(jù)
     * 默認是UTF-8
     */
    private void ParseResponseWithGson() {
        Request request = new Request.Builder()
                .url("https://api.github.com/gists/c2a7c39532239ff261be")
                .build();

        try {
            Response response = client.newCall(request).execute();
            Gist gist = gson.fromJson(response.body().charStream(), Gist.class);
            for (Map.Entry<String, GistFile> entry : gist.files.entrySet()) {
                Log.d(TAG_CONTENT, entry.getKey());
                Log.d(TAG_CONTENT, entry.getValue().content);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    static class Gist {
        Map<String, GistFile> files;
    }

    static class GistFile {
        String content;
    }


    /**
     * 緩存response
     * 首先需要一個緩存路徑,設置好緩存數(shù)據(jù)最大大小
     * 不可以在同一個緩存目錄下同時進行多個緩存,會出錯
     * 一般情況下,第一次調(diào)用時配置好緩存,其中OKHttpClient實例設置為final,
     * 之后在任意地方調(diào)用這個唯一實例即可
     *
     * response緩存使用HTTP headers來進行所有配置
     * 可以添加請求頭(request header)設置緩存失效時間,
     * 例如Cache-Control: max-stale=3600,OKHttp認可這樣的請求頭
     * 而我們的web服務器可以通過自己的響應頭(response header),
     * 例如Cache-Control: max-age=9600設置緩存失效時間
     * 如果以上兩個同時被設置,那么以時間較長的為準,單位為秒,3600指3600秒,9600指9600秒
     *
     * There are cache headers to force a cached response, force a network response,
     * or force the network response to be validated with a conditional GET.
     */
    private void CacheResponse() {
        File file = new File(Environment.getExternalStorageDirectory(), "CacheFile");

        int cacheSize = 10*1024*1024;//10MB
        Cache cache = new Cache(file, cacheSize);

        final OkHttpClient cacheClient = new OkHttpClient.Builder()
                .cache(cache)
                .build();
        Request request = new Request.Builder()
                .url("http://publicobject.com/helloworld.txt")
                .build();

        String response1Body = "";
        try {
            Response response1 = cacheClient.newCall(request).execute();
            response1Body = response1.body().string();
            Log.d(TAG_CONTENT, "Response 1 response:          " + response1);
            Log.d(TAG_CONTENT, "Response 1 cache response:    "
                    + response1.cacheResponse());
            Log.d(TAG_CONTENT, "Response 1 network response:  "
                    + response1.networkResponse());
        } catch (IOException e) {
            e.printStackTrace();
        }

        String response2Body = "";
        try {
            Response response2 = client.newCall(request).execute();
            response2Body = response2.body().string();
            Log.d(TAG_CONTENT, "Response 2 response:          " + response2);
            Log.d(TAG_CONTENT, "Response 2 cache response:    "
                    + response2.cacheResponse());
            Log.d(TAG_CONTENT, "Response 2 network response:  "
                    + response2.networkResponse());
        } catch (IOException e) {
            e.printStackTrace();
        }

        Log.d(TAG_CONTENT, "Response 2 equals Response 1? " 
+  response1Body.equals(response2Body));

    }

    /**
     * 取消網(wǎng)絡請求
     * 使用call.cancel()方法取消一個進行中的網(wǎng)絡請求
     * 如果一個線程中正在進行發(fā)起一個request或者接收一個response,那么它將收到一個IOException
     * 使用這個可以強制結(jié)束同步或異步網(wǎng)絡請求,特別是用戶退出應用時,以節(jié)約網(wǎng)絡資源
     */
    private void CancelCall() {
        Request request = new Request.Builder()
                // This URL is served with a 2 second delay.
                .url("http://httpbin.org/delay/2")
                .build();

        final long startNano = System.nanoTime();
        final Call call = client.newCall(request);
        executor.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.printf("%.5f Canceling call.%n",
                        (System.nanoTime() - startNano) / 1e9f);
                call.cancel();
                System.out.printf("%.5f Canceled call.%n",
                        (System.nanoTime() - startNano) / 1e9f);
            }
        },1, TimeUnit.SECONDS);

        System.out.printf("%.5f Executing call.%n",
                (System.nanoTime() - startNano) / 1e9f);

        try {
            Response response = call.execute();
            System.out.printf("%.5f Call was expected to fail, but completed: %s%n",
                    (System.nanoTime() - startNano) / 1e9f, response);
        } catch (IOException e) {
            System.out.printf("%.5f Call failed as expected: %s%n",
                    (System.nanoTime() - startNano) / 1e9f, e);
        }

    }

    /**
     * 配置超時
     * connectTimeout連接超時
     * writeTimeout寫入超時
     * readTimeout讀取超時
     */
    private void ConfigureTimeouts() {
        final OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .build();
        Request request = new Request.Builder()
                // This URL is served with a 2 second delay.
                .url("http://httpbin.org/delay/2")
                .build();

        try {
            Response response = client.newCall(request).execute();
            Log.d(TAG_CONTENT, "Response Completed: " + response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 在發(fā)起一個網(wǎng)絡請求前進行預配置
     *
     * OKHttp支持所有HTTP client的配置,包括代理、超時設定、緩存等等
     * 這里例子以配置readTimeOut為例
     *
     * 其實就是創(chuàng)建一個個OKHttpClient變量,然后引用唯一的OKHttpClient實例client
     * 然后按需發(fā)送網(wǎng)絡請求
     */
    private void PerCallSettings() {
        Request request = new Request.Builder()
                // This URL is served with a 1 second delay.
                .url("http://httpbin.org/delay/1")
                .build();

        //創(chuàng)建一個新的引用
        OkHttpClient copy1 = new OkHttpClient.Builder()
                .readTimeout(500, TimeUnit.MILLISECONDS)
                .build();

        try {
            Response response = copy1.newCall(request).execute();
            Log.d(TAG_CONTENT, "response 1 succeed: " + response);
        } catch (IOException e) {
            System.out.println("Response 1 failed: " + e);
        }

        //創(chuàng)建一個新的引用
        OkHttpClient copy2 = client.newBuilder()
                .readTimeout(3000, TimeUnit.MILLISECONDS)
                .build();
        try {
            Response response = copy2.newCall(request).execute();
            System.out.println("Response 2 succeeded: " + response);
        } catch (IOException e) {
            System.out.println("Response 2 failed: " + e);
        }
    }

    /**
     * 證書驗證
     *
     * OKHttp會自動重試未驗證的request
     * 當一個response包含401 Not Authorized信息,OKHttp的Authenticator接口會要求提供證書
     * 實現(xiàn)接口的過程中應該創(chuàng)建一個新的要求提供缺失證書的request,沒有可提供的證書則返回null
     *
     * 使用Response.challenges()獲取方案和認證要求(authentication challenges)
     * 當履行一個基本的認證要求時,
     * 使用Credentials.basic(username, password)編碼request header
     */
    private void Authenticate() {
        final OkHttpClient client = new OkHttpClient.Builder()
                .authenticator(new Authenticator() {
                    @Override
                    public Request authenticate(Route route, Response response)
                            throws IOException {

                        /**
                         * 也可以設定檢查驗證的次數(shù),responseCount方法在最后
                         *
                         if (responseCount(response) >= 3) {
                         return null; // If we've failed 3 times, give up.
                         }
                         */
                        if (response.request().header("Authorization") != null) {
                            // Give up, we've already attempted to authenticate.
                            return null;
                        }

                        Log.d(TAG_CONTENT, "Authenticating for response: "+ response);
                        Log.d(TAG_CONTENT, "Challenges: " + response.challenges());
                        String credential = Credentials.basic("jesse", "password1");
                        return response.request().newBuilder()
                                .header("Authorization", credential)
                                .build();
                    }
                })
                .build();

        Request request = new Request.Builder()
                .url("http://publicobject.com/secrets/hellosecret.txt")
                .build();

        try {
            Response response = client.newCall(request).execute();
            Log.d(TAG_CONTENT, response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private int responseCount(Response response) {
        int result = 1;
        while ((response = response.priorResponse()) != null) {
            result++;
        }
        return result;
    }



}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容