Android Okhttp工具类的封装

时间:2021-10-06 08:57:31
//OKhttp工具类
public class Httputils {
private OkHttpClient client;
private CallbackData callbackdata;
Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case 0:
// String str=(String) msg.obj;
callbackdata.success(msg.obj);

}
}
};

//请求网络
public <T>void getloadDemo(String url,final CallbackData callback,final Class<T> tClass){
this.callbackdata = callback;

client=new OkHttpClient.Builder()
.readTimeout(3000, TimeUnit.MILLISECONDS)
.writeTimeout(3000, TimeUnit.MILLISECONDS)
.connectTimeout(3000, TimeUnit.MILLISECONDS)
.build();

Request request = new Request.Builder().url(url).build();
okhttp3.Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(okhttp3.Call call, IOException e) {
callback.error(500,e.getMessage());
}

@Override
public void onResponse(okhttp3.Call call, Response response) throws IOException {
Message message = handler.obtainMessage();
message.what=0;
Gson gson=new Gson();
T t=gson.fromJson(response.body().string(),tClass);
message.obj=t;
handler.sendMessage(message);
}
});

}
}
-----------------------------------------------------
//所需的接口
public interface CallbackData<T> {
void success(T str);
void error(int code, String message);
}
------------------------------------------------
//Presenter类的封装
public class PresenterBean <T> {
//Model拿到请求数据 PresenterModel的交互需要接口
private final Httputils httpUtils;
private ImainView mimainView;
public PresenterBean(ImainView imainView) {
this.mimainView=imainView;
httpUtils=new Httputils();
}
//PresenterData抽成一个类 简化后的结果
public void loadDataFromServer(String url, Class<T> t,final int code){
httpUtils.getloadDemo(url, new CallbackData<T>() {
@Override
public void success(T str) {
mimainView.successCallback(str,code);
}
@Override
public void error(int code, String message) {
mimainView.errorCallback(code,message);
}
},t);

}

}
----------------------------------------------------
 
public interface ImainView <T>{    void successCallback(T str,int code);    void errorCallback(int code, String message);}
------------------------------------------------------
//RecyclerView自定义点击事件

public class RecyclerLiserner {    //点击监听 参数为view  position public interface onItemClickListener{        void onItemClick(View v, int position);    }    //长按监听 public interface onItemLongClickListener{        void onLongClick(View v, int positener);    }}
------------------------------------------
public class LiebiaoAdapter extends RecyclerView.Adapter<LiebiaoAdapter.Viewholder>implements View.OnClickListener{    private Context context;    private List<Liebiao.DatasBean.ClassListBean>mData=new ArrayList<>();    private Viewholder viewholder;    private Boolean isClicks=true;    private LayoutInflater mInflater;    private RecyclerLiserner.onItemClickListener listener;    public LiebiaoAdapter(Context context) {        this.context = context;    }    public void setData(List<Liebiao.DatasBean.ClassListBean> data){        if (data!=null){            mData.addAll(data);        }    }    //提供设置接口回调的方法 public void onItemClickListener(RecyclerLiserner.onItemClickListener listener){        this.listener=listener;    }    //因为ViewHolder我们可以拿到每个Item的根布局,所以如果我们为根布局设置单独的OnClick监听 // 并将其开放给Adapter // 那 不就可以在组装RecyclerView时就能够设置ItemClickListener // 只不过这个Listener不是设置到RecyclerView上而是设置到Adapter @Override    public Viewholder onCreateViewHolder(ViewGroup parent, int viewType){        View view = View.inflate(context, R.layout.liebiaotu, null);        view.setOnClickListener(this);        viewholder = new Viewholder(view);        return viewholder;    }    @Override    public void onBindViewHolder(Viewholder holder, final int position){        Viewholder myHolder = (Viewholder) holder;        myHolder.itemView.setTag(position);        viewholder.liebiaziti.setText(mData.get(position).getGc_name());        Glide.with(context).load("http://192.168.56.1/data/upload/mobile/category/05015382063902705.png")                .error(R.drawable.ic_action_back)                .placeholder(R.drawable.ic_item_goods)                .into(viewholder.liebiaotu);        System.out.println("myHolder = " + mData.get(position).getImage());        //x.image().bind(viewholder.liebiaotu,mData.get(position).getImage()); }    @Override    public int getItemCount() {        return mData.size();    }    @Override    public void onClick(View v) {        if (listener!=null){            listener.onItemClick(v, (Integer) v.getTag());        }    }    class Viewholder extends RecyclerView.ViewHolder{       private final ImageView liebiaotu;       private TextView liebiaziti;       public Viewholder(View itemView) {          super(itemView);            liebiaotu=   (ImageView) itemView.findViewById(R.id.liebiaotu);            liebiaziti= (TextView) itemView.findViewById(R.id.liebiaziti);       }   }}

------------------------------------------------------------
  //为recyclerView设置布局控制器   
        LinearLayoutManager manager=new LinearLayoutManager(this, LinearLayout.VERTICAL,false);
        recyclerView.setLayoutManager(manager);
       //网格视图
        GridLayoutManager gridLayoutManager=new GridLayoutManager(this,3,GridLayoutManager.VERTICAL,false);
        recyclerView.setLayoutManager(gridLayoutManager);

     //瀑布流
        StaggeredGridLayoutManager staggeredGridLayoutManager=new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(staggeredGridLayoutManager);