OKHTTP
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.Cache;
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;
/**
* Created by Dash on 2017/12/8.
*
* 公共参数封装分为两种方式....source=android,,,appVersion=100
* 一:封装到doGet和doPost方法中
*
*
* 二:封装到拦截器(interceptor):拦截一个请求,然后添加参数进去
*/
public class OkHttp3Util_03 {
/**
* 懒汉 安全 加同步
* 1.私有的静态成员变量 只声明不创建
* 2.私有的构造方法
* 3.提供返回实例的静态方法
*/
private static OkHttpClient okHttpClient = null;
private OkHttp3Util_03() {
}
public static OkHttpClient getInstance() {
if (okHttpClient == null) {
synchronized (OkHttp3Util_03.class) {
if (okHttpClient == null) {
File sdcache = new File(Environment.getExternalStorageDirectory(), "cache");
int cacheSize = 10 * 1024 * 1024;
okHttpClient = new OkHttpClient.Builder()
.connectTimeout(15, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.addInterceptor(new CommonParamsInterceptor())
.cache(new Cache(sdcache.getAbsoluteFile(), cacheSize))
.build();
}
}
}
return okHttpClient;
}
/**
* get请求
* 参数1 url
* 参数2 回调Callback
*
* oldUrl表示老的地址,,,是没封装公共参数之前的地址....公共参数指的是source=android
*
*/
public static void doGet(String oldUrl, Callback callback) {
OkHttpClient okHttpClient = getInstance();
Request request = new Request.Builder().url(oldUrl).build();
Call call = okHttpClient.newCall(request);
call.enqueue(callback);
}
/**
* post请求
* 参数1 url
* 参数2 Map<String, String> params post请求的时候给服务器传的数据
* add..("","")
* add()
*/
public static void doPost(String url, Map<String, String> params, Callback callback) {
OkHttpClient okHttpClient = getInstance();
FormBody.Builder builder = new FormBody.Builder();
for (String key : params.keySet()) {
builder.add(key, params.get(key));
}
Request request = new Request.Builder().url(url).post(builder.build()).build();
Call call = okHttpClient.newCall(request);
call.enqueue(callback);
}
/**
* post请求上传文件....包括图片....流的形式传任意文件...
* 参数1 url
* file表示上传的文件
* fileName....文件的名字,,例如aaa.jpg
* params ....传递除了file文件 其他的参数放到map集合
*
*/
public static void uploadFile(String url, File file, String fileName,Map<String,String> params,Callback callback) {
OkHttpClient okHttpClient = getInstance();
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
if (params != null){
for (String key : params.keySet()){
builder.addFormDataPart(key,params.get(key));
}
}
builder.addFormDataPart("file",fileName,RequestBody.create(MediaType.parse("application/octet-stream"),file));
MultipartBody multipartBody = builder.build();
Request request = new Request.Builder().url(url).post(multipartBody).build();
Call call = okHttpClient.newCall(request);
call.enqueue(callback);
}
/**
* Post请求发送JSON数据....{"name":"zhangsan","pwd":"123456"}
* 参数一:请求Url
* 参数二:请求的JSON
* 参数三:请求回调
*/
public static void doPostJson(String url, String jsonParams, Callback callback) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);
Request request = new Request.Builder().url(url).post(requestBody).build();
Call call = getInstance().newCall(request);
call.enqueue(callback);
}
/**
* 下载文件 以流的形式把apk写入的指定文件 得到file后进行安装
* 参数er:请求Url
* 参数san:保存文件的文件夹....download
*/
public static void download(final Activity context, final String url, final String saveDir) {
Request request = new Request.Builder().url(url).build();
Call call = getInstance().newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
InputStream is = null;
byte[] buf = new byte[2048];
int len = 0;
FileOutputStream fos = null;
try {
is = response.body().byteStream();
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();
context.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(context, "下载成功:" + fileDir + "," + getNameFromUrl(url), Toast.LENGTH_SHORT).show();
}
});
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();
}
}
});
}
/**
* 判断下载目录是否存在......并返回绝对路径
*
* @param saveDir
* @return
* @throws IOException
*/
public static String isExistDir(String saveDir) throws IOException {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File downloadFile = new File(Environment.getExternalStorageDirectory(), saveDir);
if (!downloadFile.mkdirs()) {
downloadFile.createNewFile();
}
String savePath = downloadFile.getAbsolutePath();
Log.e("savePath", savePath);
return savePath;
}
return null;
}
/**
* @param url
* @return 从下载连接中解析出文件名
*/
private static String getNameFromUrl(String url) {
return url.substring(url.lastIndexOf("/") + 1);
}
/**
* 封装公共参数的拦截器
*/
private static class CommonParamsInterceptor implements Interceptor{
@Override
public Response intercept(Chain chain) throws IOException {
Log.e("----","拦截器------");
Request request = chain.request();
String method = request.method();
String oldUrl = request.url().toString();
Map<String,String> map = new HashMap<>();
map.put("source","android");
if ("GET".equals(method)){
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(oldUrl);
if (oldUrl.contains("?")){
if (oldUrl.indexOf("?") == oldUrl.length()-1){
}else {
stringBuilder.append("&");
}
}else {
stringBuilder.append("?");
}
for (Map.Entry<String,String> entry: map.entrySet()) {
stringBuilder.append(entry.getKey())
.append("=")
.append(entry.getValue())
.append("&");
}
if (stringBuilder.indexOf("&") != -1){
stringBuilder.deleteCharAt(stringBuilder.lastIndexOf("&"));
}
String newUrl = stringBuilder.toString();
request = request.newBuilder().url(newUrl).build();
}else if ("POST".equals(method)){
Log.e("--oldUrl--",oldUrl);
RequestBody requestBody = request.body();
if (requestBody instanceof FormBody){
FormBody oldBody = (FormBody) requestBody;
FormBody.Builder builder = new FormBody.Builder();
for (int i = 0;i<oldBody.size();i++){
builder.add(oldBody.name(i),oldBody.value(i));
}
for (Map.Entry<String,String> entry: map.entrySet()) {
builder.add(entry.getKey(),entry.getValue());
}
request = request.newBuilder().url(oldUrl).post(builder.build()).build();
}
}
Response response = chain.proceed(request);
return response;
}
}
}