逝者如斯,不舍昼夜

尘世中一个迷途小书童,读书太少,想得太多
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

网络请求三方库——OkHttp

Posted on 2016-08-12 22:16  SteveWang  阅读(1160)  评论(0编辑  收藏  举报

 

  我们知道在Android开发中是可以直接使用现成的API进行网络请求的,就是使用 HttpClient 和 HttpURLConnention ,而Android 4.4 之后 HttpClient 已经被废弃,由于此前一直很流行的三方库 android-async-http 是基于 HttpClient 的,所以作者已经放弃了维护 android-async-http 库,我们在项目中也尽量不要使用这个库。

  OkHttp是Squaur公司开源的一个高性能Http请求库,它的职责同 HttpURLConnention 是一样的,支持SDPY、Http 2.0、websocket,支持同步、异步,而且OkHttp又封装了线程池、数据转换、参数使用、错误处理等,API使用起来更加方便。

  这里首先简单的介绍一下最新版 OkHttp 3.4.1 的使用以及对于同步GET和POST请求的简单封装,后续会补上异步GET和PST请求、源码解析等内容。

 

 

OkHttp同步GET、POST请求网络

 

  下面代码封装了两个使用OkHttp同步GET、POST请求网络的API,服务器返回来的都是JSON格式的字符串,而对于POST请求,客户端提交上去的也是JSON格式的字符串,源码如下:

 

/**
 * Created by stevewang on 2016/7/28.
 */
public class OkHttpUtils
{
    private static final OkHttpClient mClient = new OkHttpClient();
    public static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");

    /**
     * GET方式同步请求网络,服务器端返回JSON格式的响应
     *
     * @param urlString
     * @return
     * @throws IOException
     */
    public static String getStringFromURL(String urlString) throws IOException
    {
        // 1. 获取Request对象
        Request request = new Request.Builder()
                .url(urlString)
                .build();
        // 2. 获取Call对象
        Call call = mClient.newCall(request);
        // 3. 调用同步请求方法execute(),获取Response对象,
        Response response = call.execute();
        // 4. 获取ResponseBody对象
        ResponseBody responseBody = response.body();
        if(responseBody != null)
        {
            // 5. 从ResponseBody对象中取出服务器端返回数据
            return responseBody.string();
        }
        return null;
    }


    /**
     * POST方式同步请求网络,向服务器端提交JSON格式的请求,服务器端返回JSON格式的响应
     *
     * @param urlString
     * @param jsonRequest
     * @return
     * @throws IOException
     */
    public static  String postJsonToURL(String urlString, String jsonRequest) throws IOException
    {
        // 1. 首先构造RequestBody对象,指定了MediaType为JSON,这一步是POST请求与GET请求的主要区别
        RequestBody requestBody = RequestBody.create(MEDIA_TYPE_JSON, jsonRequest);
        // 2. 获取Request对象,将RequestBody放置到Request对象中
        Request request = new Request.Builder()
                .url(urlString)
                //                .addHeader(name, value)   // 添加请求头
                .post(requestBody)
                .build();
        // 3. 获取Call对象
        Call call = mClient.newCall(request);
        // 4. 调用同步请求方法execute(),获取Response对象,
        Response response = call.execute();
        // 5. 获取ResponseBody对象
        ResponseBody responseBody = response.body();
        if(responseBody != null)
        {
            // 6. 从ResponseBody对象中取出服务器端返回数据
            return responseBody.string();
        }
        return null;
    }
}