/** * 1、导入依赖 * 2、创建OkHttpClient对象 * 3、创建Request对象:设置请求地址,请求方式 * 4、通过OkHttpClient的newCall方法获取call对象 * 5、通过call对象调用同步:execute或者异步方法:enqueue */
CacheControl cacheControl = new CacheControl.Builder().maxAge(20, TimeUnit.MINUTES).build(); // 异步 public void sendGet() { long max = 8 * 1024 * 1024; String path = Environment.getExternalStorageDirectory().getAbsoluteFile() + "/myCache/"; File file = new File(path); if (!file.exists()) { file.mkdir(); } Cache cache = new Cache(file, max); // 框架 OkHttpClient client = new OkHttpClient.Builder().cache(cache).addInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); Response response = chain.proceed(request); Response.Builder param = response.newBuilder().removeHeader("Pragma").removeHeader("Cache-Control").addHeader("Cache-Control", "max-age=" + 1000 * 20); return param.build(); } }).build(); Request request = new Request.Builder().url("http://v.juhe.cn/toutiao/index?type=top&key=097060266650f67b2cebd2a06aded587").get().cacheControl(cacheControl).build(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { String s = response.body().string(); Gson gson = new Gson(); Message message = handler.obtainMessage(1, s.toString()); handler.sendMessage(message); } }); } public void sendGet1() { new Thread(new Runnable() { @Override public void run() { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url("http://v.juhe.cn/toutiao/index?type=top&key=097060266650f67b2cebd2a06aded587").get().build(); Call call = client.newCall(request); try { Response execute = call.execute(); String string = execute.body().string(); Gson gson = new Gson(); Message message = handler.obtainMessage(1, string.toString()); handler.sendMessage(message); } catch (IOException e) { e.printStackTrace(); } } }).start(); }