赞
踩
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.Headers;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.ConnectException;
import java.net.FileNameMap;
import java.net.SocketTimeoutException;
import java.net.URLConnection;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class OkHttpClientManager {
private static OkHttpClientManager mInstance;
private final OkHttpClient mOkHttpClient;
private final Handler mDelivery;
Context context;
private static final String TAG = "OkHttpClientManager";
private OkHttpClientManager() {
mOkHttpClient = new OkHttpClient();
//设置信任证书
mOkHttpClient.setSslSocketFactory(createSSLSocketFactory());
mOkHttpClient.setHostnameVerifier(new TrustAllHostnameVerifier());
mDelivery = new Handler(Looper.getMainLooper());
}
public static OkHttpClientManager getInstance() {
if (mInstance == null) {
synchronized (OkHttpClientManager.class) {
if (mInstance == null) {
mInstance = new OkHttpClientManager();
}
}
}
return mInstance;
}
// public static void logingetAsyn(String url, StringCallback callback) {
// getInstance()._getAsyn(url, callback);
// }
/**
* 同步的Get请求
*
* @param url
* @return Response
*/
private Response _getAsyn(String url) throws IOException {
final Request request = new Request.Builder()
.url(url)
.build();
Call call = mOkHttpClient.newCall(request);
return call.execute();
}
/**
* 同步的Get请求
*
* @param url
* @return 字符串
*/
private String _getAsString(String url) throws IOException {
Response execute = _getAsyn(url);
return execute.body().string();
}
private String _getAsString11(String url) throws IOException {
final Request request = new Request.Builder()
.url(url)
.build();
Call call = mOkHttpClient.newCall(request);
if (call.execute().isSuccessful()) {
return "200";
} else {
return "000";
}
// return "";
}
/**
* 异步的get请求
*
* @param url
* @param callback
*/
public void _getAsyn(String url, final StringCallback callback, Context context) {
final Request request = new Request.Builder()
.url(url)
.build();
deliveryResult(callback, request, context);
}
//自定义SS验证相关类
private static class TrustAllCerts implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
private static class TrustAllHostnameVerifier implements HostnameVerifier {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
private static SSLSocketFactory createSSLSocketFactory() {
SSLSocketFactory ssfFactory = null;
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, new TrustManager[]{new TrustAllCerts()}, new SecureRandom());
ssfFactory = sc.getSocketFactory();
} catch (Exception e) {
}
return ssfFactory;
}
/**
* 同步的Post请求
*
* @param url
* @param params post的参数
* @return
*/
private Response _post(String url, Param... params) throws IOException {
Request request = buildPostRequest(url, params);
return mOkHttpClient.newCall(request).execute();
}
/**
* 同步的Post请求
*
* @param url
* @param params post的参数
* @return 字符串
*/
private String _postAsString(String url, Param... params) throws IOException {
Response response = _post(url, params);
return response.body().string();
}
/**
* 异步的post请求
*
* @param url
* @param callback
* @param params
*/
public void _postAsyn(String url, final StringCallback callback, Context context, Param... params) {
Request request = buildPostRequest(url, params);
deliveryResult(callback, request, context);
}
/**
* 异步的post请求(带cookie)
*
* @param url
* @param callback
* @param params
*/
public void _postAsynCookie(String url, final StringCallback callback, String cookie, Context context, Param... params) {
Request request = buildPostRequestCooike(url, cookie, params);
deliveryResult(callback, request, context);
}
public void _postAsynCookieSP(String url, final StringCallback callback, String cookie, Context context, Map<String, String> map) {
Request request = buildPostRequestCooikeSp(url, cookie, map);
deliveryResult(callback, request, context);
}
private Request buildPostRequestCooikeSp(String url, String cookie, Map<String, String> map) {
if (map == null) {
map = new HashMap<>();
}
FormEncodingBuilder builder = new FormEncodingBuilder();
for (Map.Entry<String, String> param : map.entrySet()) {
if (param.getKey() != null && param.getValue() != null) {
builder.add(param.getKey(), param.getValue());
Log.e(TAG, "buildPostRequestCooikeSp: " + param.getKey() + "----" + param.getValue());
} else {
builder.add("", "");
}
}
RequestBody requestBody = builder.build();
return new Request.Builder()
.url(url)
.post(requestBody)
.addHeader("cookie", cookie)
.build();
}
/**
* 异步的post请求(带cookie)
*
* @param url
* @param callback
*/
public void _postAsynCookie11(String url, final StringCallback callback, String cookie, Context context) {
Request request = buildPostRequestCooike1(url, cookie);
deliveryResult(callback, request, context);
}
private Request buildPostRequestCooike1(String url, String cookie) {
FormEncodingBuilder builder = new FormEncodingBuilder();
return new Request.Builder()
.url(url)
.addHeader("cookie", cookie)
.build();
}
/**
* 异步的post请求
*
* @param url
* @param callback
* @param params
*/
public void _postAsyn(String url, final StringCallback callback, Map<String, String> params, Context context) {
Param[] paramsArr = map2Params(params);
Request request = buildPostRequest(url, paramsArr);
deliveryResult(callback, request, context);
}
/**
* 同步基于post的文件上传
*
* @param params
* @return
*/
private Response _post(String url, String[] fileName, File[] files, String[] fileKeys, Param... params) throws IOException {
Request request = buildMultipartFormRequest(url, fileName, files, fileKeys, params);
return mOkHttpClient.newCall(request).execute();
}
private Response _post(String url, String[] fileName, File file, String fileKey) throws IOException {
Request request = buildMultipartFormRequest(url, fileName, new File[]{file}, new String[]{fileKey}, null);
return mOkHttpClient.newCall(request).execute();
}
private Response _post(String url, String[] fileName, File file, String fileKey, Param... params) throws IOException {
Request request = buildMultipartFormRequest(url, fileName, new File[]{file}, new String[]{fileKey}, params);
return mOkHttpClient.newCall(request).execute();
}
/**
* 异步基于post的文件上传
*
* @param url
* @param callback
* @param files
* @param fileKeys
* @throws IOException
*/
public void _postAsyn(String url, String[] fileName, StringCallback callback, File[] files, String[] fileKeys, Context context, Param... params) throws IOException {
Request request = buildMultipartFormRequest(url, fileName, files, fileKeys, params);
deliveryResult(callback, request, context);
}
/**
* 异步基于post的文件上传
*
* @param url
* @param callback
* @param files
* @param fileKeys
* @throws IOException
*/
public void _postAsynUp(String url, StringCallback callback, File[] files, String[] fileKeys, Context context, Param... params) throws IOException {
Request request = buildMultipartFormRequestUp(url, files, fileKeys, params);
deliveryResult(callback, request, context);
}
//异步基于post的文件上传 携带cookie
public void _postAsynCookie(String url, String cookie, StringCallback callback, File[] files, String[] fileKeys, Context context, Param... params) throws IOException {
Request request = buildMultipartFormcookie(url, cookie, files, fileKeys, params);
deliveryResult(callback, request, context);
}
/**
* 异步基于post的文件上传,单文件不带参数上传
*
* @param url
* @param callback
* @param file
* @param fileKey
* @throws IOException
*/
private void _postAsyn(String url, String[] fileName, StringCallback callback, File file, String fileKey, Context context) throws IOException {
Request request = buildMultipartFormRequest(url, fileName, new File[]{file}, new String[]{fileKey}, null);
deliveryResult(callback, request, context);
}
/**
* 异步基于post的文件上传,单文件且携带其他form参数上传
*
* @param url
* @param callback
* @param file
* @param fileKey
* @param params
* @throws IOException
*/
private void _postAsyn(String url, String[] fileName, StringCallback callback, File file, String fileKey, Context context, Param... params) throws IOException {
Request request = buildMultipartFormRequest(url, fileName, new File[]{file}, new String[]{fileKey}, params);
deliveryResult(callback, request, context);
}
/**
* 异步下载文件
*
* @param url
* @param destFileDir 本地文件存储的文件夹
* @param callback
*/
public void _downloadAsyn(final String url, final String destFileDir, final StringCallback callback) {
File file1 = new File(destFileDir);
if (!file1.exists()) {
file1.mkdirs();
}
final Request request = new Request.Builder()
.url(url)
.build();
final Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(final Request request, final IOException e) {
sendFailedStringCallback(request, e, callback);
}
@Override
public void onResponse(Response response) {
InputStream is = null;
byte[] buf = new byte[2048];
int len = 0;
FileOutputStream fos = null;
try {
is = response.body().byteStream();
File file = new File(destFileDir, getFileName(url));
fos = new FileOutputStream(file);
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
}
fos.flush();
//如果下载文件成功,第一个参数为文件的绝对路径
sendSuccessStringCallback(file.getAbsolutePath(), callback);
} catch (IOException e) {
sendFailedStringCallback(response.request(), e, callback);
} finally {
try {
if (is != null) is.close();
} catch (IOException e) {
}
try {
if (fos != null) fos.close();
} catch (IOException e) {
}
}
}
});
}
private String getFileName(String path) {
int separatorIndex = path.lastIndexOf("/");
return (separatorIndex < 0) ? path : path.substring(separatorIndex + 1, path.length());
}
/**
* 加载图片
*
* @param view
* @param url
* @throws IOException
*/
private void _displayImage(final ImageView view, final String url, final int errorResId) {
final Request request = new Request.Builder()
.url(url)
.build();
Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
setErrorResId(view, errorResId);
}
@Override
public void onResponse(Response response) {
InputStream is = null;
try {
is = response.body().byteStream();
ImageUtils.ImageSize actualImageSize = ImageUtils.getImageSize(is);
ImageUtils.ImageSize imageViewSize = ImageUtils.getImageViewSize(view);
int inSampleSize = ImageUtils.calculateInSampleSize(actualImageSize, imageViewSize);
try {
is.reset();
} catch (IOException e) {
response = _getAsyn(url);
is = response.body().byteStream();
}
BitmapFactory.Options ops = new BitmapFactory.Options();
ops.inJustDecodeBounds = false;
ops.inSampleSize = inSampleSize;
final Bitmap bm = BitmapFactory.decodeStream(is, null, ops);
mDelivery.post(new Runnable() {
@Override
public void run() {
view.setImageBitmap(bm);
}
});
} catch (Exception e) {
setErrorResId(view, errorResId);
} finally {
if (is != null) try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
private void setErrorResId(final ImageView view, final int errorResId) {
mDelivery.post(new Runnable() {
@Override
public void run() {
view.setImageResource(errorResId);
}
});
}
//*************对外公布的方法************
public static Response getAsyn(String url) throws IOException {
return getInstance()._getAsyn(url);
}
public static String getAsString(String url) throws IOException {
return getInstance()._getAsString(url);
}
public static String getAsString11(String url) throws IOException {
return getInstance()._getAsString11(url);
}
// public static void getAsyn(String url, StringCallback callback) {
// getInstance()._getAsyn(url, callback);
// }
public static Response post(String url, Param... params) throws IOException {
return getInstance()._post(url, params);
}
public static String postAsString(String url, Param... params) throws IOException {
return getInstance()._postAsString(url, params);
}
// public static void postAsyn(String url, final StringCallback callback, Param... params) {
// getInstance()._postAsyn(url, callback, params);
// }
//
//
// public static void postAsyn(String url, final StringCallback callback, Map<String, String> params) {
// getInstance()._postAsyn(url, callback, params);
// }
public static Response post(String url, String[] fileName, File[] files, String[] fileKeys, Param... params) throws IOException {
return getInstance()._post(url, fileName, files, fileKeys, params);
}
public static Response post(String url, String[] fileName, File file, String fileKey) throws IOException {
return getInstance()._post(url, fileName, file, fileKey);
}
public static Response post(String url, String[] fileName, File file, String fileKey, Param... params) throws IOException {
return getInstance()._post(url, fileName, file, fileKey, params);
}
// public static void postAsyn(String url, String[] fileName, StringCallback callback, File[] files, String[] fileKeys, Param... params) throws IOException {
// getInstance()._postAsyn(url, fileName, callback, files, fileKeys, params);
// }
// public static void postAsyn(String url, String[] fileName, StringCallback callback, File file, String fileKey) throws IOException {
// getInstance()._postAsyn(url, fileName, callback, file, fileKey);
// }
//
//
// public static void postAsyn(String url, String[] fileName, StringCallback callback, File file, String fileKey, Param... params) throws IOException {
// getInstance()._postAsyn(url, fileName, callback, file, fileKey, params);
// }
public static void displayImage(final ImageView view, String url, int errorResId) throws IOException {
getInstance()._displayImage(view, url, errorResId);
}
public static void displayImage(final ImageView view, String url) {
getInstance()._displayImage(view, url, -1);
}
public static void downloadAsyn(String url, String destDir, StringCallback callback) {
getInstance()._downloadAsyn(url, destDir, callback);
}
//****************************
private Request buildMultipartFormRequestUp(String url, File[] files,
String[] fileKeys, Param[] params) {
params = validateParam(params);
MultipartBuilder builder = new MultipartBuilder()
.type(MultipartBuilder.FORM);
for (int x = 0; x < files.length; x++) {
builder.addFormDataPart("media", files[x].getName(), RequestBody.create(MediaType.parse("image/png"), files[x]));
}
for (Param param : params) {
builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + param.key + "\""),
RequestBody.create(null, param.value));
}
if (files != null) {
RequestBody fileBody = null;
for (int i = 0; i < files.length; i++) {
File file = files[i];
String fileName = file.getName();
fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileName)), file);
//TODO 根据文件名设置contentType
builder.addPart(Headers.of("Content-Disposition",
"form-data; name=\"" + fileKeys[i] + "\"; filename=\"" + fileName + "\""),
fileBody);
}
}
RequestBody requestBody = builder.build();
return new Request.Builder()
.url(url)
.post(requestBody)
.build();
}
private Request buildMultipartFormcookie(String url, String cookie, File[] files,
String[] fileKeys, Param[] params) {
params = validateParam(params);
MultipartBuilder builder = new MultipartBuilder()
.type(MultipartBuilder.FORM);
//<!--这两段是干啥的?-->
// for (int x = 0; x < files.length; x++) {
// builder.addFormDataPart("media", files[x].getName(), RequestBody.create(MediaType.parse("image/png"), files[x]));
// }
//
// for (Param param : params) {
// builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + param.key + "\""),
// RequestBody.create(null, param.value));
//
// }
if (files != null) {
RequestBody fileBody = null;
for (int i = 0; i < files.length; i++) {
File file = files[i];
String fileName = file.getName();
fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileName)), file);
//TODO 根据文件名设置contentType
builder.addPart(Headers.of("Content-Disposition",
"form-data; name=\"" + fileKeys[i] + "\"; filename=\"" + fileName + "\""),
fileBody);
}
}
RequestBody requestBody = builder.build();
return new Request.Builder()
.url(url)
.post(requestBody)
.addHeader("cookie", cookie)
.build();
}
private Request buildMultipartFormRequest(String url, String[] fileNamey, File[] files,
String[] fileKeys, Param[] params) {
params = validateParam(params);
MultipartBuilder builder = new MultipartBuilder()
.type(MultipartBuilder.FORM);
for (Param param : params) {
builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + param.key + "\""),
RequestBody.create(null, param.value));
}
if (files != null) {
RequestBody fileBody = null;
for (int i = 0; i < files.length; i++) {
File file = files[i];
String fileName = fileNamey[i];
fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileName)), file);
//TODO 根据文件名设置contentType
builder.addPart(Headers.of("Content-Disposition",
"form-data; name=\"" + fileKeys[i] + "\"; filename=\"" + fileName + "\""),
fileBody);
}
}
RequestBody requestBody = builder.build();
return new Request.Builder()
.url(url)
.post(requestBody)
.build();
}
private String guessMimeType(String path) {
FileNameMap fileNameMap = URLConnection.getFileNameMap();
String contentTypeFor = fileNameMap.getContentTypeFor(path);
if (contentTypeFor == null) {
contentTypeFor = "application/octet-stream";
}
return contentTypeFor;
}
private Param[] validateParam(Param[] params) {
if (params == null)
return new Param[0];
else return params;
}
private Param[] map2Params(Map<String, String> params) {
if (params == null) return new Param[0];
int size = params.size();
Param[] res = new Param[size];
Set<Map.Entry<String, String>> entries = params.entrySet();
int i = 0;
for (Map.Entry<String, String> entry : entries) {
res[i++] = new Param(entry.getKey(), entry.getValue());
}
return res;
}
private void deliveryResult(final StringCallback callback, final Request request, final Context context) {
mOkHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);//设置连接超时时间
mOkHttpClient.setReadTimeout(30, TimeUnit.SECONDS);
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(final Request request, final IOException e) {
sendFailedStringCallback(request, e, callback);
//
// if (MyApplication.Isshow == 0) {
// MyApplication.Isshow = 1;
// if (getNetWorkInfo(context) != 1) {
// new Thread(new Runnable() {
// @Override
// public void run() {
// Looper.prepare();
// AlertDialog("连接超时请检查网络!请重新登录...", context);
// Looper.loop();//增加部分
// }
// }).start();
//
// }
// }
}
@Override
public void onResponse(final Response response) {
try {
final String string = response.body().string();
sendSuccessStringCallback(string, callback);
} catch (IOException e) {
sendFailedStringCallback(response.request(), e, callback);
}
}
});
}
// 判断手机的网络状态(是否联网)
public static int getNetWorkInfo(Context context) {
//网络状态初始值
int type = -1; //-1(当前网络异常,没有联网)
//通过上下文得到系统服务,参数为网络连接服务,返回网络连接的管理类
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
//通过网络管理类的实例得到联网日志的状态,返回联网日志的实例
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
//判断联网日志是否为空
if (activeNetworkInfo == null) {
//状态为空当前网络异常,没有联网
return type;
}
//不为空得到使用的网络类型
int type1 = activeNetworkInfo.getType();
switch (type1) {
case ConnectivityManager.TYPE_MOBILE: //网络类型为运营商(移动/联通/电信)
type = 0;
break;
case ConnectivityManager.TYPE_WIFI: //网络类型为WIFI(无线网)
type = 1;
break;
default:
type = -1;
break;
}
//返回网络类型
return type;
}
private void AlertDialog(final String strContent, final Context context) {
LayoutInflater factory = LayoutInflater.from(context);
View myView = factory.inflate(R.layout.exit_dialog, null);
final Dialog dialog = new AlertDialog.Builder(context)
.setView(myView).create();
//设置点击Dialog外部任意区域关闭Dialog
dialog.setCanceledOnTouchOutside(true);
dialog.show();
//设置弹窗在底部
Window window = dialog.getWindow();
window.setGravity(Gravity.CENTER);
final Button btn_cancel = dialog.findViewById(R.id.btn_cancel);
final Button btn_sure = dialog.findViewById(R.id.btn_sure);
final TextView textView6 = dialog.findViewById(R.id.textView6);
btn_cancel.setVisibility(View.GONE);
textView6.setText(strContent);
LinearLayout linear_edpass = dialog.findViewById(R.id.linear_edpass);
final EditText edit_pass = dialog.findViewById(R.id.edit_pass);
textView6.setVisibility(View.VISIBLE);
linear_edpass.setVisibility(View.GONE);
btn_sure.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
VSGService.getInstance().logout(context, null);
context.startActivity(new Intent(context, LoginActivity.class));
}
});
btn_cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
private void sendFailedStringCallback(final Request request, final IOException e, final StringCallback callback) {
mDelivery.post(new Runnable() {
@Override
public void run() {
if (callback != null)
callback.onFailure(request, e);
}
});
}
private void sendSuccessStringCallback(final String string, final StringCallback callback) {
mDelivery.post(new Runnable() {
@Override
public void run() {
if (callback != null)
callback.onResponse(string);
}
});
}
private Request buildPostRequest(String url, Param[] params) {
if (params == null) {
params = new Param[0];
}
FormEncodingBuilder builder = new FormEncodingBuilder();
for (Param param : params) {
if (param.key != null && param.value != null) {
builder.add(param.key, param.value);
} else {
builder.add("", "");
}
}
RequestBody requestBody = builder.build();
return new Request.Builder()
.url(url)
.post(requestBody)
.build();
}
private Request buildPostRequestCooike(String url, String cookie, Param[] params) {
if (params == null) {
params = new Param[0];
}
FormEncodingBuilder builder = new FormEncodingBuilder();
for (Param param : params) {
if (param.key != null && param.value != null) {
builder.add(param.key, param.value);
} else {
builder.add("", "");
}
}
RequestBody requestBody = builder.build();
return new Request.Builder()
.url(url)
.post(requestBody)
.addHeader("cookie", cookie)
.build();
}
public interface StringCallback {
void onFailure(Request request, IOException e);
void onResponse(String response);
}
public static class Param implements Serializable {
public Param() {
}
public Param(String key, String value) {
this.key = key;
this.value = value;
}
String key;
String value;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
public static String toStr(Param[] params) {
String strParams = "";
for (Param param : params) {
strParams = strParams + "{" +
"key:'" + param.key + '\'' +
", value:'" + param.value + '\'' +
"},";
}
return "[" + strParams + "]";
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。