首先导入okhttp
compile 'com.squareup.okhttp3:okhttp:3.7.0'
封装的主要类
OkHttpHelper主要是封装的OkHttpClient以及请求参数的封装 BaseCallback 辅助类 SpotsCallBack加载的提示框,可以更改
OkHttpHelper类
首先把它做成一个单例
private static class singleHolder {
private static final OkHttpHelper instance = new OkHttpHelper();
}
private OkHttpHelper() {
okHttpClient = new OkHttpClient().newBuilder()
.readTimeout(10, TimeUnit.SECONDS)//设置读取超时时间
.writeTimeout(10, TimeUnit.SECONDS)//设置写的超时时间
.connectTimeout(10, TimeUnit.SECONDS)//设置连接超时时间
.build();
mGson = new Gson();
mHandler = new Handler(Looper.getMainLooper());
}
public static OkHttpHelper getInstance() {
return singleHolder.instance;
}
在封装BaseCallback因为我们要根据它得到类型
static Type getSuperclassTypeParameter(Class<?> subclass) {
Type superclass = subclass.getGenericSuperclass();
if (superclass instanceof Class) {
throw new RuntimeException("Missing type parameter.");
}
ParameterizedType parameterizedType = (ParameterizedType) superclass;
return $Gson$Types.canonicalize(parameterizedType.getActualTypeArguments()[0]);
}
然后在封装doRequest方法
private void doRequest(Request request, final BaseCallback callback) {
callback.onRequestBefore(request);
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
callback.onFailure(call.request(), e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
callback.OnResponse(response);
if (response.isSuccessful()) {
if (callback.mType == String.class) {
String resultStr = response.body().string();
LogHelper.i("String 请求到的数据:" + resultStr);
callbackSuccess(callback, response, resultStr);
} else if (("" + callback.mType).equals("byte[]")) {
byte[] resultStr = response.body().bytes();
LogHelper.i("byte 请求到的数据:" + resultStr);
callbackSuccess(callback, response, resultStr);
} else {
try {
String resultStr = response.body().string();
LogHelper.i("json 请求到的数据:" + resultStr);
Object object = mGson.fromJson(resultStr, callback.mType);
callbackSuccess(callback, response, object);
} catch (Exception e) {
e.printStackTrace();
callbackError(callback, response, response.code(), e);
}
}
} else {
callback.onError(response, response.code(), null);
}
}
});
}
最后测试
//请求参数
Map<String, String> map = new HashMap<>();
OkHttpHelper.getInstance().post("请求的地址", map, new SpotsCallBack<BannerClazz>(UIUtils.getContext(), false) {
@Override
public void onSuccess(Response response, BannerClazz bannerClazz) {
iBannerInterface.bannerSuccess(bannerClazz);
}
@Override
public void onError(Response response, int code, Exception e) {
}
});
下边贴出完整代码
import android.os.Handler;
import android.os.Looper;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class OkHttpHelper {
private static OkHttpClient okHttpClient;
private Gson mGson;
private Handler mHandler;
private static class singleHolder {
private static final OkHttpHelper instance = new OkHttpHelper();
}
private OkHttpHelper() {
okHttpClient = new OkHttpClient().newBuilder()
.readTimeout(10, TimeUnit.SECONDS)//设置读取超时时间
.writeTimeout(10, TimeUnit.SECONDS)//设置写的超时时间
.connectTimeout(10, TimeUnit.SECONDS)//设置连接超时时间
.build();
mGson = new Gson();
mHandler = new Handler(Looper.getMainLooper());
}
public static OkHttpHelper getInstance() {
// return new OkHttpHelper();
return singleHolder.instance;
}
private void doRequest(Request request, final BaseCallback callback) {
callback.onRequestBefore(request);
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
callback.onFailure(call.request(), e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
callback.OnResponse(response);
if (response.isSuccessful()) {
if (callback.mType == String.class) {
String resultStr = response.body().string();
LogHelper.i("String 请求到的数据:" + resultStr);
callbackSuccess(callback, response, resultStr);
} else if (("" + callback.mType).equals("byte[]")) {
byte[] resultStr = response.body().bytes();
LogHelper.i("byte 请求到的数据:" + resultStr);
callbackSuccess(callback, response, resultStr);
} else {
try {
String resultStr = response.body().string();
LogHelper.i("json 请求到的数据:" + resultStr);
Object object = mGson.fromJson(resultStr, callback.mType);
callbackSuccess(callback, response, object);
} catch (Exception e) {
e.printStackTrace();
callbackError(callback, response, response.code(), e);
}
}
} else {
callback.onError(response, response.code(), null);
}
}
});
}
public void get(String url, BaseCallback callback) {
Request request = buildRequest(url, null, HttpMethodType.GET);
doRequest(request, callback);
}
public void post(String url, Map<String, String> params, BaseCallback callback) {
Request request = buildRequest(url, params, HttpMethodType.POST);
doRequest(request, callback);
}
public void file(String url, String localPath, BaseCallback callback) {
if (!CommonUtil.getInstance().judgeStrIsNull(url) &&
!CommonUtil.getInstance().judgeStrIsNull(localPath)) {
File file = new File(localPath);
if (!file.exists()) {
LogHelper.e("该路径下找不到此文件");
return;
}
RequestBody body = RequestBody.create(MediaType.parse("image/*"), file);
// 初始化请求体对象,设置Content-Type以及文件数据流
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM) // multipart/form-data
.addFormDataPart("file", file.getName(), body)
.build();
Request request = new Request.Builder().url(url).post(requestBody).build();
doRequest(request, callback);
} else {
LogHelper.e("本地路径或者服务器上传路径为空");
}
}
private Request buildRequest(String url, Map<String, String> params, HttpMethodType methodType) {
Request.Builder builder = new Request.Builder();
builder.url(url);
LogHelper.i("Request Url::" + url);
if (methodType == HttpMethodType.GET) {
builder.get();
} else if (methodType == HttpMethodType.POST) {
RequestBody body = buildFormData(params);
builder.post(body);
}
return builder.build();
}
private RequestBody buildFormData(Map<String, String> params) {
FormBody.Builder body = new FormBody.Builder();
if (params != null) {
for (Map.Entry<String, String> entry : params.entrySet()) {
try {
LogHelper.i("key::" + entry.getKey() + "--value::" + entry.getValue());
if (!CommonUtil.getInstance().judgeStrIsNull(entry.getKey())) {
body.add(entry.getKey(), entry.getValue());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
return body.build();
}
enum HttpMethodType {
GET, POST
}
private void callbackSuccess(final BaseCallback callback, final Response response, final Object object) {
mHandler.post(new Runnable() {
@Override
public void run() {
callback.onSuccess(response, object);
}
});
}
private void callbackError(final BaseCallback callback, final Response response, final int code, final Exception e) {
mHandler.post(new Runnable() {
@Override
public void run() {
callback.onError(response, code, e);
}
});
}
}
public abstract class BaseCallback<T> {
Type mType;
public BaseCallback() {
mType = getSuperclassTypeParameter(getClass());
}
static Type getSuperclassTypeParameter(Class<?> subclass) {
Type superclass = subclass.getGenericSuperclass();
if (superclass instanceof Class) {
throw new RuntimeException("Missing type parameter.");
}
ParameterizedType parameterizedType = (ParameterizedType) superclass;
return $Gson$Types.canonicalize(parameterizedType.getActualTypeArguments()[0]);
}
public abstract void onRequestBefore(Request request);
public abstract void onFailure(Request request, IOException e);
public abstract void onSuccess(Response response, T t);
public abstract void onError(Response response, int code, Exception e);
public abstract void OnResponse(Response response);
}
public abstract class SpotsCallBack<T> extends BaseCallback<T> {
private SpotsDialog dialog;
private boolean isShow = true;
public SpotsCallBack(Context context) {
try {
dialog = new SpotsDialog(context);
} catch (Exception e) {
e.printStackTrace();
}
setMessage("加载中......");
}
public SpotsCallBack(Context context, boolean show) {
this.isShow = show;
if(isShow){
try {
dialog = new SpotsDialog(context);
} catch (Exception e) {
e.printStackTrace();
}
}
setMessage("加载中......");
}
public SpotsCallBack(Context context, String message) {
try {
dialog = new SpotsDialog(context);
} catch (Exception e) {
e.printStackTrace();
}
if (!TextUtils.isEmpty(message)) {
setMessage(message);
}
}
protected void showDialog() {
try {
if (dialog != null) {
dialog.show();
}
} catch (Exception e) {
//e.printStackTrace();
}
}
protected void dismissDialog() {
try {
if (dialog != null)
dialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
protected void setMessage(String message) {
try {
if (dialog != null) {
dialog.setMessage(message);
}
} catch (Exception e) {
// e.printStackTrace();
}
}
@Override
public void onRequestBefore(Request request) {
if (isShow)
showDialog();
}
@Override
public void onFailure(Request request, IOException e) {
dismissDialog();
}
@Override
public void OnResponse(Response response) {
dismissDialog();
}
}