public class HttpUtil { static HttpUtil util; private final OkHttpClient client; // 私有化构造方法 private HttpUtil(){ client = new OkHttpClient(); } public static HttpUtil getInstance(){ if(util == null){ synchronized (HttpUtil.class){ util = new HttpUtil(); } } return util; } public void httRequest(String url,final HttpRespon respon) { Request request = new Request.Builder() .url(url) .build(); client.newCall(request).enqueue(new Callback() { // 请求失败 @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); respon.onError("请求网络失败"); } // 有响应 @Override public void onResponse(Call call, Response response) throws IOException { if (!response.isSuccessful()) { respon.onError("请求网络失败"); } // 获取响应body String json = response.body().string(); // 解析Json respon.parse(json); } }); } }
定义的回调接口:
public abstract class HttpRespon<T> { //http返回的类型的泛型 Class<T> t; public HttpRespon(Class<T> t){ this.t = t; } // 请求失败时,回调的方法 public abstract void onError(String msg); // 请求成功时,回调的方法 public abstract void onSuccess(T t); public void parse(String json){ if(TextUtils.isEmpty(json)){ //请求失败 onError("连接网络失败"); return; } if(t == String.class){ onSuccess((T) json); return; } T result = JsonUtil.parse(json, this.t); if(result == null){ onError("Json解析失败"); }else{ onSuccess(result); } } }
调用的事例:
HttpUtil.getInstance().httRequest(Constant.SPLASH_URL, new HttpRespon<Ad>(Ad.class) { @Override public void onError(String msg) { Log.i("fjl", msg); } @Override public void onSuccess(Ad ad) { Intent intent = new Intent(); intent.setClass(AdsActivity.this, AdDownloadService.class); intent.putExtra(AdDownloadService.AD_DATA, ad); startService(intent); } });
原文地址:https://www.cnblogs.com/kliver123/p/8761846.html
时间: 2024-12-26 22:39:02