package com.example.jd.model.https;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
public class HttpsUntils implements Callback {
private static HttpsUntils INSTANCE;
private final OkHttpClient okHttpClient;
//单列模式
public static HttpsUntils getInstance() {
if (INSTANCE == null) {
synchronized (HttpsUntils.class) {
if (INSTANCE == null) {
INSTANCE = new HttpsUntils();
}
}
}
return INSTANCE;
}
//okhttp
public HttpsUntils() {
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
okHttpClient = new OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)
.build();
}
//get请求
private HttpCallback mhttpCallback;
public String doGet(String path, HttpCallback httpCallback) {
this.mhttpCallback = httpCallback;
Request request = new Request.Builder().url(path).build();
Call call = okHttpClient.newCall(request);
call.enqueue(this);
return "";
}
//post
public String doPost(String path, HashMap<String, String> map, HttpCallback httpCallback) {
this.mhttpCallback = httpCallback;
FormBody.Builder builder = new FormBody.Builder();
//遍历map
Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
String value = map.get(key);
builder.add(key, value);
}
FormBody formBody = builder.build();
Request request = new Request.Builder().url(path).post(formBody).build();
Call call = okHttpClient.newCall(request);
call.enqueue(this);
return "";
}
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String string = response.body().string();
mhttpCallback.onSuccess(string);
}
}