MyTask类
package com.example.okhttpdemo;
import android.os.Environment;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* Created by leon on 2017/12/19.
*/
public class MyOkHttp {
private OkHttpClient ok;
private Cache cache;
private long maxSize = 8 * 1024 * 1024 ;
private static MyOkHttp okHttp = new MyOkHttp();
private MyOkHttp(){
//获取手机根目录并在根目录下建一个文件夹:
//Environment是用来管理手机SDCard内存的
File file = new File( Environment.getExternalStorageDirectory() + "/H1706A");
cache = new Cache( file,maxSize );
ok = new OkHttpClient.Builder().cache( cache ).build();
}
public static MyOkHttp getOkHttp(){
return okHttp;
}
//同步get请求:
public String sendGet(String url) throws IOException {
Request request = new Request.Builder().url( url ).build();
Response response = ok.newCall( request ).execute();
String string = response.body().string();
return string;
}
//同步post请求:
public String sendPost(String url, FormBody body) throws IOException {
Request request = new Request.Builder().url( url ).post( body ).build();
Response response = ok.newCall( request ).execute();
String s = response.body().string();
return s;
}
//异步get请求:
public void sendGetAnsy(String url,Callback callback) throws IOException {
Request request = new Request.Builder().url( url ).build();
ok.newCall( request ).enqueue( callback );;
}
//异步post请求:
public void sendPostAnsync(String url,FormBody body,Callback callback){
Request request = new Request.Builder().url( url ).post( body ).build();
ok.newCall( request ).enqueue( callback );
}
//测试缓存:
public String sendCacheGet(String url) throws IOException {
Request request = new Request.Builder().url( url ).cacheControl( new CacheControl.Builder().maxStale( 24*60*60, TimeUnit.DAYS ).build() ).build();
Response response = ok.newCall( request ).execute();
String s = response.body().string();
return s;
}
}