public class OKhttpUtils {
private static final String TAG = "OKhttpUtils--";
private static OKhttpUtils oKhttpUtils;
private final OkHttpClient okHttpClient;
private final Handler myHandler;
public OKhttpUtils() {
myHandler = new Handler(Looper.getMainLooper());
okHttpClient = new OkHttpClient.Builder().addInterceptor(new MyInterceptor()).build();
}
public static OKhttpUtils getoKhttpUtils() {
if (oKhttpUtils == null) {
synchronized (OKhttpUtils.class) {
if (oKhttpUtils == null) {
return oKhttpUtils = new OKhttpUtils();
}
}
}
return oKhttpUtils;
}
public void doGet(String url, final IOKhttpCallBack ioKhttpCallBack) {
Request request = new Request.Builder()
.get()
.url(url)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
if (ioKhttpCallBack != null) {
myHandler.post(new Runnable() {
@Override
public void run() {
ioKhttpCallBack.onFaild(e.getMessage());
}
});
}
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response != null && response.isSuccessful()) {
final String json = response.body().string();
if (ioKhttpCallBack != null) {
myHandler.post(new Runnable() {
@Override
public void run() {
ioKhttpCallBack.onSuccess(json);
}
});
}
} else {
if (ioKhttpCallBack != null) {
myHandler.post(new Runnable() {
@Override
public void run() {
ioKhttpCallBack.onFaild("网络异常");
}
});
}
}
}
});
}
public void doPost(String url, Map<String, String> map, final IOKhttpCallBack ioKhttpCallBack) {
FormBody.Builder builder = new FormBody.Builder();
for (String key : map.keySet()) {
String value = map.get(key);
Log.d(TAG, "doPost: "+key+value);
builder.add(key, value);
}
FormBody formBody = builder.build();
Request request = new Request.Builder()
.post(formBody)
.url(url)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
if (ioKhttpCallBack != null) {
myHandler.post(new Runnable() {
@Override
public void run() {
ioKhttpCallBack.onFaild(e.getMessage());
}
});
}
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response != null && response.isSuccessful()) {
final String json = response.body().string();
Log.d(TAG, "onResponse: "+json);
if (ioKhttpCallBack != null) {
myHandler.post(new Runnable() {
@Override
public void run() {
ioKhttpCallBack.onSuccess(json);
}
});
}
} else {
if (ioKhttpCallBack != null) {
myHandler.post(new Runnable() {
@Override
public void run() {
ioKhttpCallBack.onFaild("网络异常");
}
});
}
}
}
});
}
public interface IOKhttpCallBack {
void onFaild(String error);
void onSuccess(String json);
}
}