okhttp的二次封装(基本使用)

来源:互联网 发布:emc测试 知乎 编辑:程序博客网 时间:2024/06/06 05:49

           OKhttp,我们都知道,是当前特别受欢迎的框架,但是还是有存在着它的缺点,比如:冗余的对象,大量固定且反复的代码,,在开发过程中,效率有待提高,而且对应用的性能也是,待优化,,

      所以就有了ok的二次封装,接下来就进入主题.

       在封装之前,我们需要了解需要干什么,这么做的目的,,,我在这里就只是简单实现功能,主要是了解二次封装的思路,,以及单例模式这种常用的设计模式,,

          我们需要

节约内存  
简化代码通过使用单例模式进行实现大致思路就这样:::::::
定义成员变量
使用构造方式,完成初始化
使用单例模式,通过获取的方式拿到对象
定义接口
使用handler,保证处理数据的逻辑在主线程

新建 类
public class OkhttpManager {        /////////////////////////// 定义成员变量 ////////////////////    private OkHttpClient okHttpClient;    private static Handler handler;    private volatile static OkhttpManager manager;    //////////////////////////使用构造方式,完成初始化///////////////////////////    private OkhttpManager(){        okHttpClient = new OkHttpClient();        handler = new Handler();    }    //////////////////////////使用单例模式,通过获取的方式拿到对象//////////////////////////////    public static OkhttpManager getInstance(){        OkhttpManager instance = null;        if (instance == null){            synchronized (OkhttpManager.class){                if (instance == null){                    instance = new OkhttpManager();                    manager = instance;                }            }        }        return instance;    }    //////////////////////////定义接口///////////////////////    interface  Func1{        void onResponse(String result);    }    interface  Func2{        void onResponse(byte[] result);    }    interface  Func3{        void onResponse(Bitmap result);    }    interface Function4{        void onResponse(JSONObject jsonObject);    }    /////////////////////////使用handler没借口,保证处理数据的逻辑在主线程//////////////////////    //处理请求网络成功的方法,返回的结果是json字符串    private static void onSuccessJsonStringMethod(final String Jsonvalue,final Func1 callBack){        //这里我用的是handler.post方法把数据放到主线程    以后可以用eventbus 或者RxJava去完成        handler.post(new Runnable() {            @Override            public void run() {                if (callBack != null ){                    try{                        callBack.onResponse(Jsonvalue);                    }catch (Exception e){                        e.printStackTrace();                    }                }            }        });    }    private static void onSuccessJsonStringMethod(final Bitmap jsonValue, final Func3 callBack){        //这里使用Handler.post 把数据放到主线程,也可以使用EventBus或RxJava的线程调度器去完成        handler.post(new Runnable() {            @Override            public void run() {                if(callBack != null){                    try {                        callBack.onResponse(jsonValue);                    } catch (Exception e) {                        e.printStackTrace();                    }                }            }        });    }    //处理请求网络成功的方法,返回的结果是json字符串    private static void onSuccessJsonStringMethod(final byte[] buffer,final Func2 callBack){        //这里我用的是handler.post方法把数据放到主线程    以后可以用eventbus 或者RxJava去完成        handler.post(new Runnable() {            @Override            public void run() {                if (callBack != null ){                    try{                        callBack.onResponse(buffer);                    }catch (Exception e){                        e.printStackTrace();                    }                }            }        });    }    /////////////////////////暴露提供给外界调用的方法////////////////////////////////////    /**     * 请求指定的URL返回的结果是JSon字符串     */    public void asyncJsonStringByURL(String url,final Func1 callBack){        Request request = new Request.Builder().url(url).build();        okHttpClient.newCall(request).enqueue(new Callback() {            @Override            public void onFailure(Call call, IOException e) {            }            @Override            public void onResponse(Call call, Response response) throws IOException {                // !!!! 判断response是否有对象 , 成功                if (response!=null&&response.isSuccessful()){                    onSuccessJsonStringMethod(response.body().string(),callBack);                }            }        });    }    public  void  downLoadImage(String url,final Func3 callBack){        Request request = new Request.Builder().url(url).build();        okHttpClient.newCall(request).enqueue(new Callback() {            @Override            public void onFailure(Call call, IOException e) {            }            @Override            public void onResponse(Call call, Response response) throws IOException {                //先判断response不为null                if(response != null && response.isSuccessful()){                    InputStream inputStream = response.body().byteStream();                    onSuccessJsonStringMethod(BitmapFactory.decodeStream(inputStream),callBack);                }            }        });    }    /**     * 提交表单     *     */    public void sendComplexForm(String url, Map<String,String> parms,final Func2 callback){        //表单队像        FormBody.Builder form_builder = new FormBody.Builder();        //键值非空判断        if (parms != null && !parms.isEmpty()){            for (Map.Entry<String,String> entry : parms.entrySet()){                form_builder.add(entry.getKey(),entry.getValue());            }        }        final FormBody reqest_body = form_builder.build();        Request request = new Request.Builder().url(url).post(reqest_body).build();        okHttpClient.newCall(request).enqueue(new Callback() {            @Override            public void onFailure(Call call, IOException e) {            }            @Override            public void onResponse(Call call, Response response) throws IOException {                onSuccessJsonStringMethod(response.body().bytes(), new Func2() {                    @Override                    public void onResponse(byte[] result) {                    }                });            }        });    }}做完封装后,在main方法中进行功能的实现实现
public class MainActivity extends AppCompatActivity {    private String json_path = "http://publicobject.com/helloworld.txt";    private String Login_path = "http://169.254.53.96:8080/web/LoginServlet";    private String Picture_path = "https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1504746675&di=044790278fab83b8be4c0e78c473b32e&src=http://pic.nipic.com/2008-05-12/200851273819966_2.jpg";    private ImageView mImageView;    private OkhttpManager okhttpManager;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        okhttpManager = OkhttpManager.getInstance();        mImageView = (ImageView) findViewById(R.id.imageView);    }    /**     * 通过点击事件执行okhttp里封装的根据网址,获取字符串的逻辑操作.     *     * @param view     */    public void okhttp_json(View view) {        okhttpManager.asyncJsonStringByURL(json_path, new OkhttpManager.Func1() {            @Override            public void onResponse(String result) {                Toast.makeText(MainActivity.this,result,Toast.LENGTH_LONG).show();            }        });    }    //像服务器提交账号及密码    public void okhttp_table(View view) {        HashMap<String, String> map = new HashMap<>();        map.put("qq","10000");        map.put("pwd","abcde");//            okhttpManager.sendComplexForm(Login_path, map, new )        okhttpManager.sendComplexForm(Login_path, map, new OkhttpManager.Func2() {            @Override            public void onResponse(byte[] result) {                Toast.makeText(MainActivity.this,"打开",Toast.LENGTH_SHORT).show();            }        });        Toast.makeText(MainActivity.this,"关闭",Toast.LENGTH_SHORT).show();    }    //下载图片    public void okhttp_picture(View view) {        okhttpManager.downLoadImage("https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1504746675&di=044790278fab83b8be4c0e78c473b32e&src=http://pic.nipic.com/2008-05-12/200851273819966_2.jpg", new OkhttpManager.Func3() {            @Override            public void onResponse(Bitmap result) {                mImageView.setImageBitmap(result);            }        });    }}
 下面是布局文件
<Button    android:onClick="okhttp_json"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text="获取Json数据"    android:layout_alignParentTop="true"    android:layout_centerHorizontal="true"    android:id="@+id/button2"/><Button    android:onClick="okhttp_table"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text="表单提交"    android:id="@+id/button3"    android:layout_below="@+id/button2"    android:layout_centerHorizontal="true"/><Button    android:onClick="okhttp_picture"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text="下载图片"    android:layout_below="@+id/button3"    android:layout_centerHorizontal="true"/><ImageView    android:layout_width="100dp"    android:layout_height="100dp"    android:id="@+id/imageView"    android:layout_alignParentBottom="true"    android:layout_centerHorizontal="true"/><TextView    android:id="@+id/textview"    android:layout_width="wrap_content"    android:layout_height="wrap_content" />



原创粉丝点击