Okhttp的封裝和回調
阿新 • • 發佈:2018-04-09
error nbsp put turn 解析失敗 span oid nal xtu
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) throwsIOException { 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); } });
Okhttp的封裝和回調