OkHttp3用法

转载:写的很详细,可下载demo
Android网络编程(六)OkHttp3用法全解析

测试上传文件时,可以把文件上传到
https://api.github.com/markdown/raw 里

还有这篇文章
OKHttp3.0的日常及入门

Retrofit2.0+okhttp3缓存机制以及遇到的问题

使用Retrofit和Okhttp实现网络缓存。无网读缓存,有网根据过期时间重新请求

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\n" + 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\n" + 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\n" + response.body().toString());}

                log("asynGet\n" + 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();
            }
        });
    }
}

你可能感兴趣的:(网络请求)