import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
private static OkHttp3Utils okHttp3Utils = null;
}
if (okHttp3Utils == null) {
//加同步安全
synchronized (OkHttp3Utils.class) {
if (okHttp3Utils == null) {
okHttp3Utils = new OkHttp3Utils();
}
}
}
if (okHttpClient == null) {
//判空 爲空創建實例
// okHttpClient = new OkHttpClient();
//緩存目錄
File sdcache = new File(Environment.getExternalStorageDirectory(), "cache");
int cacheSize = 10 * 1024 * 1024;
//OkHttp3攔截器
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
Log.i("xxx", message.toString());
}
});
//Okhttp3的攔截器日誌分類 4種
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
okHttpClient = new OkHttpClient.Builder().connectTimeout(15, TimeUnit.SECONDS)
//添加OkHttp3的攔截器
.addInterceptor(httpLoggingInterceptor)
.addNetworkInterceptor(new CacheInterceptor())
.writeTimeout(20, TimeUnit.SECONDS).readTimeout(20, TimeUnit.SECONDS)
.cache(new Cache(sdcache.getAbsoluteFile(), cacheSize))
.build();
}
return okHttpClient;
}
if (mHandler == null) {
mHandler = new Handler();
}
}
OkHttpClient okHttpClient = getOkHttpClient();
//創建Request
Request request = new Request.Builder().url(url).build();
//得到Call對象
Call call = okHttpClient.newCall(request);
//執行異步請求
call.enqueue(callback);
}
public static void doPost(String url, Map<String, String> params, Callback callback) {
OkHttpClient okHttpClient = getOkHttpClient();
//3.x版本post請求換成FormBody 封裝鍵值對參數
//遍歷集合
for (String key : params.keySet()) {
builder.add(key, params.get(key));
//創建Request
Request request = new Request.Builder().url(url).post(builder.build()).build();
call.enqueue(callback);
Call call = okHttpClient.newCall(request);
//執行請求
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
public void onResponse(Call call, Response response) throws IOException {
//上傳成功回調 目前不需要處理
}
});
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);
Request request = new Request.Builder().url(url).post(requestBody).build();
Call call = getOkHttpClient().newCall(request);
call.enqueue(callback);
}
Request request = new Request.Builder().url(url).build();
Call call = getOkHttpClient().newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i("xxx", e.toString());
}
public void onResponse(Call call, final Response response) throws IOException {
byte[] buf = new byte[2048];
int len = 0;
FileOutputStream fos = null;
try {
is = response.body().byteStream();
//apk保存路徑
final String fileDir = isExistDir(saveDir);
//文件
File file = new File(fileDir, getNameFromUrl(url));
fos = new FileOutputStream(file);
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
}
fos.flush();
//apk下載完成後 調用系統的安裝方法
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
context.startActivity(intent);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) is.close();
if (fos != null) fos.close();
}
}
});
public static String isExistDir(String saveDir) throws IOException {
// 下載位置
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
if (!downloadFile.mkdirs()) {
downloadFile.createNewFile();
}
String savePath = downloadFile.getAbsolutePath();
Log.e("savePath", savePath);
return savePath;
}
return null;
}
return url.substring(url.lastIndexOf("/") + 1);
}
@Override
public Response intercept(Chain chain) throws IOException {
int maxAge = 60 * 60;
Request request = chain.request();
if (NetWorkUtils.isNetWorkAvailable(MyApp.getInstance())) {
request = request.newBuilder().cacheControl(CacheControl.FORCE_NETWORK).build();
} else {
/* Looper.prepare();
Toast.makeText(MyApp.getInstance(), "走攔截器緩存", Toast.LENGTH_SHORT).show();
Looper.loop();*/
}
Response response = chain.proceed(request);
if (NetWorkUtils.isNetWorkAvailable(MyApp.getInstance())) {
response = response.newBuilder()
.removeHeader("Pragma")
.header("Cache-Control", "public, max-age=" + maxAge)
.build();
} else {
response = response.newBuilder()
.removeHeader("Pragma")
.header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
.build();
}
return response;
}
}
public interface OnGetServerDateLisnter {
void getData(String string);
}
}