OkHttp的使用和封装

OkHttp的使用和封装

转载请标明出处:
http://blog.csdn.net/lxy_cn/article/details/52775984
本文出自:【李晓阳的博客

在工作中最容易遇到问题之一那就是网络编程,互联网时代没有网络服务的应用是没有价值的,可以说在你参加工作后,这就是必备的,人道:“工欲善其事,必先利其器”一个好的轮子能为你的工作从效率和质量上出现质的飞升,至于为什么把okhttp作为首选我只说一点,据说Android4.0后Google采用了okhttp作为Android的底层网络框架,其价值不言而喻,有大神作为背书,那我就不废话了就让我们开始吧!

本篇博客首先介绍okhttp的简单使用和封装,主要包含:


OkHttp的引入

(1)eclipse开发环境下

下载最新的 okhttp.jarokio.jar >两个jar包并且添加依赖就可以用了。
注意:okhttp内部依赖okio,别忘了同时导入okio

(2)Androidstudio开发环境下

在gradle中添加依赖:
compile ‘com.squareup.okhttp:okhttp:2.4.0’
compile ‘com.squareup.okio:okio:1.5.0’

好啦截止这里okhttp已经在你的项目中可以开始使用啦!We are GO!


GET请求

同步get请求

 /**
     * GET请求
     *
     * @param urlString 请求URL
     * @return request请求
     */
    private static Request getRequestFormUrl(String urlString) {
        Request request = new Request.Builder()
                .url(urlString)
                .build();
        return request;
    }

    /**
     * GET同步请求
     *
     * @param urlString 请求URL
     * @return response响应对象
     * @throws IOException
     */
    private static Response buildResponseFromUrl(String urlString) throws IOException {
        Request request = getRequestFormUrl(urlString);
        Response response = okHttpClient.newCall(request).execute();
        return response;
    }

    /**
     * GET同步请求
     *
     * @param urlString 请求
     * @return responseBody对象
     * @throws IOException
     */
    private static ResponseBody buildResponseBodyFormUrl(String urlString) throws IOException {
        Response response = buildResponseFromUrl(urlString);
        ResponseBody responseBody = response.body();
        return responseBody;
    }

根据responseBody,我们就可以获取string、byte、stream类型的响应数据

 /**
     * GET同步请求
     *
     * @param urlString 请求
     * @return 返回字符串结果
     * @throws IOException
     */
    public static String getStringFormUrl(String urlString) throws IOException {
        ResponseBody responseBody = buildResponseBodyFormUrl(urlString);
        return responseBody.string();
    }

    /**
     * GET同步请求
     *
     * @param urlString 请求URL
     * @return 返回byte字节
     * @throws IOException
     */
    public static byte[] getByteFormUrl(String urlString) throws IOException {
        ResponseBody responseBody = buildResponseBodyFormUrl(urlString);
        return responseBody.bytes();
    }

    /**
     * GET同步请求
     *
     * @param urlString 请求URL
     * @return 返回输入流
     * @throws IOException
     */
    public static InputStream getStreamForUrl(String urlString) throws IOException {
        ResponseBody responseBody = buildResponseBodyFormUrl(urlString);
        return responseBody.byteStream();
    }

同步get请求封装

//get同步网络请求
                //网络请求需要在子线程中进行
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String string =MyOkhttpUtils.
                            getStringFormUrl(UrlUtils.GET_URL);

                            Message msg = Message.obtain();
                            msg.what = SUCCESS;
                            msg.obj = "同步GET请求" + string;
                            handler.sendMessage(msg);
                        } catch (IOException e) {
                            e.printStackTrace();

                            handler.sendEmptyMessage(ERROR);
                        }
                    }
                }).start();

异步get请求

 /**
     * GET异步请求
     *
     * @param urlString 请求URL
     * @param callback  返回接口
     */
    public static void loadDataFormUrlAsync(String urlString, Callback callback) {
        Request request = getRequestFormUrl(urlString);
        okHttpClient.newCall(request).enqueue(callback);
    }

异步get请求封装

//get异步网络请求 (本身就在子线程之中)
                MyOkhttpUtils.loadDataFormUrlAsync(UrlUtils.GET_URL, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        //请求失败(网络异常)
                        handler.sendEmptyMessage(ERROR);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String string = response.body().string();
                        //获得相应response对象
                        Message msg = Message.obtain();
                        msg.what = SUCCESS;
                        msg.obj = "异步GET请求" + string;
                        handler.sendMessage(msg);
                    }
                });

POST请求

post同步请求

    /**
     * POST请求
     * @param map 数据键值对
     * @return requestBody对象
     */
    private static RequestBody buildRequestBody(Map<String, String> map) {
        FormBody.Builder builder = new FormBody.Builder();
        if (map != null && !map.isEmpty()) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                builder.add(entry.getKey(),entry.getValue());
            }

        }
        return builder.build();
    }

    private static RequestBody buildJsonRequestBody(String jsonString){
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        RequestBody requestBody = RequestBody.create(mediaType, jsonString);
        return requestBody;
    }

    /**
     * POST同步请求
     *
     * @param urlString   请求url
     * @param requestBody 请求体
     * @return Request请求对象
     */
    private static Request buildPostRequest(String urlString, RequestBody requestBody) {
        Request.Builder builder = new Request.Builder();
        builder.post(requestBody);
        return builder.build();
    }

    /**
     * POST同步请求
     * @param urlString 请求URL
     * @param requestBody 请求体requestBody对象
     * @return 返回responseBody对象
     * @throws IOException
     */
    private static ResponseBody postRsponseBody(String urlString,RequestBody requestBody) throws IOException {
        Request request = buildPostRequest(urlString, requestBody);
        Response response = okHttpClient.newCall(request).execute();
        if(response.isSuccessful()){
            return response.body();
        }
        return null;
    }

 /**
     * POST同步方式发送键值对请求
     * @param urlString 请求URL
     * @param map 键值对数据
     * @return  响应字符串类型数据
     * @throws IOException
     */
    public static String postKeyValuePair(String urlString,Map<String,String> map) throws IOException {
        RequestBody requestBody = buildRequestBody(map);
        ResponseBody responseBody = postRsponseBody(urlString, requestBody);
        return responseBody.string();

    }

 /**
     * POST同步发送JSON字符串
     * @param urlString 请求URL
     * @param jsonString 
     * @return
     * @throws IOException
     */
    public static String postJsonStringPair(String urlString,String jsonString) throws IOException {
        RequestBody requestBody = buildJsonRequestBody(jsonString);
        ResponseBody responseBody = postRsponseBody(urlString, requestBody);
        return responseBody.string();

    }

post同步请求封装

//post同步请求(键值对数据)
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //请求参数:page=1&code=news&pageSize=20&parentid=0&type=1
                        Map<String, String> map = new HashMap<String, String>();
                        map.put("page1", "1");
                        map.put("code", "news");
                        map.put("pageSize", "20");
                        map.put("parentid", "0");
                        map.put("type", "1");
                        try {
                            String postString = MyOkhttpUtils.postKeyValuePair(UrlUtils.POST_URL, map);
                            Message msg = Message.obtain();
                            msg.what = SUCCESS;
                            msg.obj = "post同步请求" + postString;
                            handler.sendMessage(msg);

                        } catch (IOException e) {
                            e.printStackTrace();
                            handler.sendEmptyMessage(ERROR);
                        }
                    }
                }).start();

post异步请求

/**
     * POST异步请求
     * @param urlString 请求URL
     * @param requestBody 请求体
     * @param callback 异步POST请求回调
     */
    private static void postResponseBodyAsync(String urlString,RequestBody requestBody,Callback callback) {
        Request request = buildPostRequest(urlString, requestBody);
        okHttpClient.newCall(request).enqueue(callback);

    }

/**
     * POST异步方式发送键值对请求
     * @param urlString 请求URL
     * @param map 键值对数据
     * @param callback post异步请求回调
     */
    public static void postKeyValuePairAsync(String urlString,Map<String,String> map,Callback callback){
        RequestBody requestBody = buildRequestBody(map);
        postResponseBodyAsync(urlString,requestBody,callback);
    }

    /**
     * POST异步发送JSON字符串请求
     * @param urlString  请求URL
     * @param jsonString JSON字符串
     * @param callback   post请求回调
     */
    public static void postJsonStringPairAsync(String urlString,String jsonString,Callback callback){
        RequestBody requestBody=buildJsonRequestBody(jsonString);
        postResponseBodyAsync(urlString,requestBody,callback);
    }

post异步请求封装

Map<String, String> map = new HashMap<String, String>();
                map.put("name", "xiaoming");
                map.put("passworld", "123456");
                //post异步请求(键值对数据)
                OkhttpUtils.postKeyValuePairAsync(UrlUtils.GET_URL, map, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        handler.sendEmptyMessage(ERROR);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String postString = response.body().string();
                        Message msg = Message.obtain();
                        msg.what = SUCCESS;
                        msg.obj = "post异步请求" + postString;
                        handler.sendMessage(msg);
                    }
                });

基于http的文件上上传(上传也属于post请求)

 //同时上传文件和提交用户名  模仿的是浏览器的过程
    File file = new File(Environment.getExternalStorageDirectory(), "wenjianming.txt");

    RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);

    //请求体   文件名字用 (文件名+当前时间戳) 
    RequestBody  requestBody = new MultipartBody.Builder("")
            .setType(MultipartBody.FORM)
            .addPart(Headers.of("Content-Disposition","form-data; name=\"username\""),RequestBody.create(null,"李晓阳"))
            .addPart(Headers.of("Content-Disposition", "form-data; filename=\""+System.currentTimeMillis()+file.getName()+"\""), fileBody)
            .build();
    //请求
    Request request = new Request.Builder()
            .url("http://192.168.1.11:8080/okHttp3Server/fileUpload")
            .post(requestBody)
            .build();

拿到request就好办了同理get 和post 既可以设置同步也可以设置异步


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值