我对Okhttp的再次封装,间接易用,高效快速

昨天对Android 的网络库 okhttp进行了二次封装

//整个类就是这个样子
public  class httpOk {
//    使用弱引用 防止内存泄漏
// 	这里解释一下原因,因为handle是属于UI主线程的,但是网络连接是在另一个线程,异步获取
//	如果主线程由于各种不可知因素被销毁,那么这里的引用依然在,gc就不会回收handle对象,容易造成内存泄漏
// 	所以使用弱引用 而不是强引用
    private WeakReference<Handler> handlerWeakReference;
//    该对象
    private httpOk ho;

    private String url;

    private Object data;

    private int identification;

    public  httpOk  () {

    }
// 这几个方法都是 用来初始化 
    public  httpOk addHandler(WeakReference<Handler> handlerWeakReference) {
        this.handlerWeakReference = handlerWeakReference;
        return this;
    }
    public httpOk addUrl (String url){
        this.url=url;
        return this ;
    }

    public httpOk addData (Object obj){
        this.data = obj;
        return this;
    }

    public httpOk addIdentification(int identification){
        this.identification = identification;
        return this;
    }
// 发送请求
    public void postJson(){

        OkHttpClient client = new OkHttpClient();//创建client
        MediaType json = MediaType.parse("application/json; charset=utf-8");
//        User user = new User("lixin",18,"188282ll","lixin888");
        Gson gson = new Gson();
        String jStr = gson.toJson(data,data.getClass());
        RequestBody requestBody = RequestBody.create(json,jStr);
        final Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("testjosn","no ok");
            }
// 加入异步线程 ,斌设置成功后的回调函数
            @Override
            public void onResponse(Call call, Response response) throws IOException {
//                Log.i("testjosn",""+response.body().string());
                Handler handler = handlerWeakReference.get();
                //判断一下handle 是否被回收 如果回收掉了 即使访问成功 也啥都不做
                if (handler==null){
//                    nothing to Do
                }else{
                // 封装一下message 
                    Message message = Message.obtain();
                    message.what = identification;
                    Bundle b = new Bundle();
                    // 这里是个大坑  .string() 方法只能调用一次 应为一旦读出内容,文件流就会关闭
                    b.putString("hello",response.body().string());
                    message.setData(b);
                    //发送出去
                    handler.sendMessage(message);
                }
            }
        });
    }
}

这是ui线程的代码

public class TwoFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private httpOk httpok= new httpOk();
    private Button send;
    private TextView textView;
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public TwoFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment TwoFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static TwoFragment newInstance(String param1, String param2) {
        TwoFragment fragment = new TwoFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view=  inflater.inflate(R.layout.fragment_two, container, false);

        send = view.findViewById(R.id.sendJson);
        textView = view.findViewById(R.id.receiveText);
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            // 这里
                httpok
                //设置handler
                       .addHandler(new WeakReference<Handler>(new myhandle()))
                       //设置 url
                       .addUrl("http://172.23.161.166:8080/lixin01_war_exploded/home/json");
                User user = new User("lixin",18,"123456","666");
                //加入数据
                httpok.addData(user);
                //设置标识
                httpok.addIdentification(0x01);
                
                httpok.postJson();
            }
        });
        return view;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

 
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

//    handle 中执行对网络的请求
    private static  class  myhandle extends Handler{
//        private  final WeakReference<Activity> mActivityRefrence;
// 弱引用
    /*
    * 当该 activity 被回收掉了 ,那么 弱应用 就可以 保证 不 会出现内存溢出
    *
    * */
//        private myhandle(WeakReference<Activity> mActivityRefrence) {
//            this.mActivityRefrence = mActivityRefrence;
//        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
//            MainActivity mainActivity = (MainActivity) mActivityRefrence.get();//获取弱引用的对象
            switch (msg.what){
                case 0x01:
                    Bundle bundle = msg.getData();
                    Log.i("testNet",""+bundle.getString("hello"));
                    break;
                case 2:

                    break;
            }

        }

}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值