public class OkHttpUtils {
private static OkHttpUtils instance;
private final Handler mHandler;
private OkHttpClient mOkHttpClient;
private OkHttpUtils(){
mOkHttpClient = new OkHttpClient.Builder()
.readTimeout(10, TimeUnit.SECONDS)
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.build();
//创建主线程的handler
mHandler = new Handler(Looper.getMainLooper());
}
//单例模式
public static OkHttpUtils getInstance(){
if (instance == null){
synchronized (OkHttpUtils.class){
if (instance == null){
instance = new OkHttpUtils();
}
}
}
return instance;
}
//post请求
public void doPost(String url, Map<String,String> map , final OkCallBack okCallBack){
//创建 FormBody对象
FormBody.Builder builder = new FormBody.Builder();
if (map != null){
for (String key : map.keySet()){
builder.add(key,map.get(key));
}
}
//把表单添加到formBody中
FormBody formBody = builder.build();
//创建request对象
Request request = new Request.Builder()
.post(formBody)
.url(url)
.build();
//创建Call对象
Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
if (okCallBack != null){
mHandler.post(new Runnable() {
@Override
public void run() {
okCallBack.Failed(e);
}
});
}
}
@Override
public void onResponse(Call call, Response response) throws IOException {
try {
if (response != null && response.isSuccessful()){
final String json = response.body().string();
if (okCallBack != null){
mHandler.post(new Runnable() {
@Override
public void run() {
okCallBack.Success(json);
return;
}
});
}
}
} catch (IOException e) {
e.printStackTrace();
}
if (okCallBack != null){
okCallBack.Failed(new Exception("网络异常"));
}
}
});
}
//get请求
public void doGet(String url, final OkCallBack okCallBack){
Request request = new Request.Builder().url(url).build();
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
if (okCallBack != null){
mHandler.post(new Runnable() {
@Override
public void run() {
okCallBack.Failed(e);
}
});
}
}
@Override
public void onResponse(Call call, Response response) throws IOException {
try {
if (response != null && response.isSuccessful()){
final String json = response.body().string();
if (okCallBack != null){
mHandler.post(new Runnable() {
@Override
public void run() {
okCallBack.Success(json);
return;
}
});
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
public interface OkCallBack {
void Success(String json);
void Failed(Exception e);
}