封装工具类
public class HttoUtils2 { private NetDataCallBack netDataCallback; private Handler mhand=new Handler(); public <T> void getdata(String url, final NetDataCallBack netDataCallback, final Class<T> tclass) { //初始化一个 OkHttpClient 并且设置连接和读取超时时间 OkHttpClient okhttp = new OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS) .readTimeout(20, TimeUnit.SECONDS) .build(); //构造一个Request对象 Request request = new Request.Builder().url(url).build(); //通过request的对象去构造得到一个Call对象 Call call = okhttp.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { netDataCallback.faild(499,e.getMessage()); } @Override public void onResponse(Call call, Response response) throws IOException { String string = response.body().string(); Gson gson=new Gson(); T t = gson.fromJson(string, tclass); final Message msg = Message.obtain(); msg.what=ok; msg.obj=t; mhand.post(new Runnable() { @Override public void run() { netDataCallback.success(msg.obj); } }); } }); } //post请求 public <T>void getLoadDataPost(String url, final NetDataCallBack netDataCallback, final Class<T> tClass, RequestBody body){ this.netDataCallback = netDataCallback; OkHttpClient okHttpClient = new OkHttpClient.Builder() .readTimeout(20, TimeUnit.SECONDS) .connectTimeout(10, TimeUnit.SECONDS) .build(); final Request request = new Request.Builder().url(url).post(body).build(); Call call = okHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { netDataCallback.faild(499,e.getMessage()); } @Override public void onResponse(Call call, Response response) throws IOException { T t = new Gson().fromJson(response.body().string(), tClass); final Message msg = Message.obtain(); msg.what = OK; msg.obj = t; mhand.post(new Runnable() { @Override public void run() { netDataCallback.success(msg.obj); } }); } }); } }
创建接口
public interface NetDataCallBack<T> { void success(T t); void faild(int positon, String str); }
Activity运用
implements NetDataCallBack<Data>
public void aaa(){ HttoUtils2 utils2 = new HttoUtils2(); utils2.getdata(url,this,Data.class); } @Override public void success(Data data) { } @Override public void faild(int positon, String str) { }