OkHTTP请求封装
public class OkhttpUtils {
private final OkHttpClient okHttpClient;
private final Handler handler;
//单例模式
private OkhttpUtils() {
okHttpClient = new OkHttpClient.Builder()
.connectTimeout(1000, TimeUnit.SECONDS)
.readTimeout(1000, TimeUnit.SECONDS)
.writeTimeout(1000, TimeUnit.SECONDS)
.build();
handler = new Handler();
}
private static OkhttpUtils okhttpUtils = null;
public static OkhttpUtils getOkhttpUtils() {
if (okhttpUtils == null) {
okhttpUtils = new OkhttpUtils();
}
return okhttpUtils;
}
//接口回调json串
public interface Fun1 {
void getResultJson(String String);
}
private Fun1 fun1;
public void getSuccessJson(String url, final Fun1 fun1) {
final Request request = new Request.Builder().url(url).build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String s = response.body().string();
handler.post(new Runnable() {
@Override
public void run() {
fun1.getResultJson(s);
}
});
}
});
}
}
本文介绍了一个基于OkHTTP的封装方案,通过单例模式创建OkHttpClient,并设置连接、读取及写入超时时间。该封装支持GET请求,利用接口回调方式处理JSON响应,简化了网络请求流程。
429

被折叠的 条评论
为什么被折叠?



