OkHttp 3の使い方


転載:詳しく書いてありますが、demo Androidネットワークプログラミング(六)OkHttp 3用法全解析をダウンロードできます.
ファイルのアップロードをテストするときは、ファイルをhttps://api.github.com/markdown/raw内
そしてこの記事.0の日常および入門
Retrofit2.0+okhttp 3キャッシュメカニズムおよび問題点
RetrofitとOkhttpを使用してネットワークキャッシュを実現します.≪ネット・リード・キャッシュなし|No Net Read Cache|emdw≫:有効期限に従ってネットが再要求されます.
public class MainActivity extends AppCompatActivity {

    private OkHttpClient mOkHttpClient;
    private String url_post = "http://v.juhe.cn/weixin/query";
    String key = "cccccc";
    String url_get = "http://v.juhe.cn/weixin/query?pno=&ps=&dtype=&key=cccccc";
    private OkHttpClient mOkHttpClientCach;

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


    private void initOkHttp() {
        Interceptor interceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                Log.e("cach", "request=" + request);
                Response response = chain.proceed(request);
                Log.e("cach", "response=" + response);



                String cacheControl = request.cacheControl().toString();
                if (TextUtils.isEmpty(cacheControl)) {
                    cacheControl = "public, max-age=60";
                }
                return response.newBuilder()
                        .header("Cache-Control", cacheControl)
                        .removeHeader("Pragma")
                        .build();
            }
        };

        // 
        File sdcache = new File(getFilesDir(), "cccccccc");

        // 
        int cacheSize = 10 * 1024 * 1024;
        okhttp3.Cache cache = new okhttp3.Cache(sdcache, cacheSize);

        mOkHttpClientCach= new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .cache(cache)
                .addNetworkInterceptor(interceptor)//★★★ addNetworkInterceptor, addInterceptor
                .build();




    }

    public void asynGet(View view) {
        mOkHttpClient = new OkHttpClient();

        Request request = new Request.Builder().get().url(url_get).build();
        mOkHttpClientCach.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                toast("asynGet: ");
                log(e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                toast("asynGet: ");
                log("asynGet
"
+ response.body().string()); } }); } /** * post get RequestBody Request , onResponse UI 。 * * @param view */ public void asynPost(View view) { mOkHttpClient = new OkHttpClient(); // post FormBody formBody = new FormBody.Builder().add("key", key).add("pno", "3").build(); // ,url+ Request request = new Request.Builder().post(formBody).url(url_post).build(); // mOkHttpClientCach.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { toast("asynPost: "); log(e.toString()); } @Override public void onResponse(Call call, Response response) throws IOException { toast("asynPost: "); log("asynPost
"
+ response.body().string()); } }); } public void asynGetCache(View view) { Request request = new Request.Builder() .url(url_get) .cacheControl(CacheControl.FORCE_NETWORK) .build(); mOkHttpClientCach.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { toast("asynGetCache: "); log(e.toString()); } @Override public void onResponse(Call call, Response response) throws IOException { toast("asynGetCache: "); if (response.cacheResponse()!=null){ log("asynGet:cacheResponse
"
+ response.body().toString());} log("asynGet
"
+ response.networkResponse().toString()); } }); } private void log(String msg) { Log.e("okhttp", msg); } private void toast(final String msg) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplication(), msg, Toast.LENGTH_SHORT).show(); } }); } }