import android.os.Handler;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
public class OkHttpManager {
private OkHttpClient httpClient;
private Handler handler;
/************************/
private OkHttpManager(){
initOkHttp();
}
private static class OkHttpManagerHolder{
private static OkHttpManager manager = new OkHttpManager();
}
public static OkHttpManager getInstance(){
return OkHttpManagerHolder.manager;
}
/************************/
private void initOkHttp() {
handler = new Handler();
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.connectTimeout(10,TimeUnit.SECONDS)
.readTimeout(10,TimeUnit.SECONDS)
.writeTimeout(10,TimeUnit.SECONDS)
.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));
httpClient = builder.build();
}
public void doGet(String url,final AsyncCallBack callBack){
Request request = new Request.Builder()
.url(url)
.build();
httpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(final Call call, IOException e) {
handler.post(new Runnable() {
@Override
public void run() {
if (callBack!=null){
callBack.Fail("error");
}
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()){
final String s = response.body().string();
handler.post(new Runnable() {
@Override
public void run() {
if (callBack!=null){
callBack.Success(s);
}
}
});
}else {
if (callBack!=null){
callBack.Fail("");
}
}
}
});
}
public interface AsyncCallBack{
void Success(String data);
void Fail(String data);
}
}
okhttp网络封装类的简单实现
最新推荐文章于 2019-05-25 11:23:43 发布