package com.example.ggq.gaoguoqing20180811.utils;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class OkHttpUtil {
private static final OkHttpUtil ourInstance = new OkHttpUtil();
private OkHttpClient okHttpClient;
public static OkHttpUtil getInstance() {
return ourInstance;
}
private OkHttpUtil() {
okHttpClient = new OkHttpClient.Builder()
.connectTimeout(5,TimeUnit.SECONDS)
.writeTimeout(5,TimeUnit.SECONDS)
.readTimeout(5,TimeUnit.SECONDS)
.build();
}
private RequestCallback requestCallback;
public OkHttpUtil(RequestCallback requestCallback) {
this.requestCallback = requestCallback;
}
public void postData(String url, HashMap<String,String> params, final RequestCallback callback){
FormBody.Builder builder = new FormBody.Builder();
if(params != null && params.size()>0){
for (Map.Entry<String, String> stringStringEntry : params.entrySet()) {
builder.add(stringStringEntry.getKey(),stringStringEntry.getValue());
}
}
Request request = new Request
.Builder()
.url(url)
.post(builder.build())
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
if(callback != null){
callback.onError(e);
}
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if(callback != null){
callback.onSuccess(response);
}
}
});
}
public interface RequestCallback{
void onSuccess(Response response);//数据请求成功
void onError(IOException e);//数据请求失败
}
}
配置Apppublic class App extends Application {
@Override
public void onCreate() {
super.onCreate();
ZXingLibrary.initDisplayOpinion(this);
}
}