• 网络请求三方库——OkHttp


      我们知道在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;
        }
    }
  • 相关阅读:
    G 面经 && Leetcode: Longest Repeating Character Replacement
    Leetcode: Reconstruct Original Digits from English
    Leetcode: Maximum XOR of Two Numbers in an Array
    Leetcode: Battleships in a Board
    Leetcode: Find All Anagrams in a String
    Leetcode: Pacific Atlantic Water Flow
    Leetcode: Partition Equal Subset Sum
    Leetcode: Third Maximum Number
    Leetcode: Arithmetic Slices
    Leetcode: Trapping Rain Water II
  • 原文地址:https://www.cnblogs.com/eniac12/p/5766753.html
Copyright © 2020-2023  润新知