Android OK
2018-12-10 本文已影响0人
人心所向便是阳光
public class OkHttpUtil {
private static final String METHOD_GET = "GET";
private static final String METHOD_POST = "POST";
public static OkHttpClient okHttpClient;
public OkHttpUtil() {
}
public static void init() {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.connectTimeout(5000, TimeUnit.MILLISECONDS);
builder.writeTimeout(5000, TimeUnit.MILLISECONDS);
builder.readTimeout(5000, TimeUnit.MILLISECONDS);
builder.addInterceptor(new OkHeaderInterceptor());
builder.addInterceptor(new OkLogInterceptor());
okHttpClient = builder.build();
}
private static Request createRequest(String url, String method, HashMap baseRequest) {
FormBody requestBody = null;
if (baseRequest != null) {
FormBody.Builder formBuilder = new FormBody.Builder();
Set set = baseRequest.keySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
String key = (String) iterator.next();
String value = (String) baseRequest.get(key);
formBuilder.add(key, value);
}
requestBody = formBuilder.build();
}
Request.Builder builder = new Request.Builder().url(url);
Request request = null;
switch (method) {
case METHOD_GET:
request = builder.build();
break;
case METHOD_POST:
request = builder.post(requestBody).build();
break;
}
return request;
}
public static void enqueueGET(String url,Callback callback) {
Request request = createRequest(url, METHOD_GET, null);
Call call = okHttpClient.newCall(request);
call.enqueue(callback);
}
public static void enqueuePOST(String url, HashMap hashMap, OkHttpCallBack okHttpCallBack) {
Request request = createRequest(url,METHOD_POST, hashMap);
Call call = okHttpClient.newCall(request);
call.enqueue(okHttpCallBack);
}
}