OkHttp3 -- 基本使用

记得大学校招面试时候 , 被问到网络框架 . 当时就弱鸡的说 , 只会基础的 , 还没开始玩框架 – – 那今天来谈谈当时想说不敢说的框架OkHttp吧

gradle依赖:

compile 'com.squareup.okhttp3:okhttp:3.3.0'

get请求

  1. 获取Request对象
    Request是OKHttp中访问的请求,Builder为辅助类
  2. 获取Response对象
    获取Call对象,调用该对象的execute方法
  3. 获取RequestBody对象
    通过Response对象的body方法获取
  4. 从ResponseBody中获取服务端返回的数据
    服务端返回的书库都在responseBody响应对象中, 通过相应体的不同方法可以获取到不同的对象
  • 以上四个步骤对应如下代码 , 自己写的工具类
public class OkHttpUtilForGET {
    private static final OkHttpClient client=new OkHttpClient();

    /**
     * 获取request(请求)对象
     */
    private Request getRequestFromUrl(String url){
        Request request=new Request.Builder().url(url).build();
        return request;
    }
    /**
     * 获取Response(响应)对象
     */
    private Response getResponseFromUrl(String url) throws IOException {
        Request request=getRequestFromUrl(url);
        Response response=client.newCall(request).execute();
        return response;
    }
    /**
     * 获取ResponseBody对象
     */
    private ResponseBody getResponseBodyFromUrl(String url) throws IOException {
        Response response=getResponseFromUrl(url);
        if (response.isSuccessful()){
            //响应成功
            return response.body();
        }
        return null;
    }
    /**
     * 从ResponseBody中获取数据
     */
    public String LoadStringFromUrl(String url) throws IOException {
        ResponseBody body=getResponseBodyFromUrl(url);
        if (body!=null){
            return body.string(); //此处可以获取各种数据,如byte[],InputStream等
        }else {
            return null;
        }
    }

    /**
     * 开启异步线程,通过实现回调方法来实现数据的加载
     */
    public void loadDataByNewThread(String url, Callback callback){
        Request request = getRequestFromUrl(url); //获得request对象
        client.newCall(request).enqueue(callback); // 此处需要实现回调方法
    }
}

使用该工具类中的LoadStringFromUrl时 , 必须在子线程中:

new Thread(new Runnable() {
    @Override
    public void run() {
        /**
         * 使用OkHttpUtilForGet
         */
        OkHttpUtilForGet util = new OkHttpUtilForGet();
        String msg = util.loadStringFromUrl(url)
    }
}).start();

使用异步请求的话 , 需要实现回调方法

OkHttpUtilForGet util=new OkHttpUtilForGet();
util.LoadDataByNewThread(url, new Callback() {
    @Override
    public void onFailure(Request request, IOException e) {
        //执行错误的时候
    }

    @Override
    public void onResponse(Response response) throws IOException {
        //执行成功的时候
        if (response.isSuccessful()) {
            ResponseBody body = response.body();
            //得到body
            //使用handler更新界面,此处位于子线程
        }
    }
});

POST请求

  1. 在FormEncodingBuidler对象中放置键值对数据
  2. 获取RequestBody请求体对象
  3. 获取Request对象,讲RequestBody放置到Request对象中
  4. 获取Response对象
  5. 获取ResponseBody对象
  6. 从ResponseBody对象中拿到最终的数据
public class OkHttpUtilForPost {
    private static final OkHttpClient client = new OkHttpClient();

     /**
     * 通过POST网络访问提交键值对--------------------->步骤1
     */
    public static String postKeyValuePairs(String url, Map<String, String> map) throws IOException {
        RequestBody body = buildRequestBody(map);
        return postRequestBody(url, body);
    }
    
    /**
     * 通过POST发送RequestBody对象//------------------->步骤2
     */
    private static String postRequestBody(String url, RequestBody body) throws IOException {
        Request request = buildPostRequest(url, body);
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            return response.body().string(); //请求成功
        }
        return null;
    }

    /**
     * 构建Post请求的Request对象//------------------->步骤3
     */
    private static Request buildPostRequest(String url, RequestBody body) {
        Request.Builder builder = new Request.Builder();
        builder.url(url).post(body);
        return builder.build();
    }

    /**
     * 构建RequestBody对象<此处为键值对>
     */
    private static RequestBody buildRequestBody(Map<String, String> map) {
        FormEncodingBuilder builder = new FormEncodingBuilder();//-------------->步骤1
        if (map != null && map.isEmpty()) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                builder.add(entry.getKey(), entry.getValue());
            }
        }
        return builder.build();
    }
   
    /**
     * post异步网络请求
     */
    private static void postRequestBodyAsync(String url, RequestBody body, Callback callback) {
        Request request = buildPostRequest(url, body);
        client.newCall(request).enqueue(callback);
    }
    /**
     * post异步网络请求,提交键值对
     */
    public static void postKeyValuePairAsync(String url, Map<String,String> map, Callback callback){
        RequestBody body=buildRequestBody(map);
        postRequestBodyAsync(url,body,callback);
    }
}

使用工具类:

/**
 * Post同步提交
 */
final Map<String,String> map=new HashMap<>();
map.put("123","123");
new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            String result=OkHttpUtilForPost.postKeyValuePairs(url,map);
            new Handler().post(new Runnable() {
                @Override
                public void run() {
                    //更新UI
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}).start();

/**
 * Post异步提交
 */
OkHttpUtilForPost.postKeyValuePairAsync(url, map, new Callback() {
    @Override
    public void onFailure(Request request, IOException e) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                //UI
            }
        });
    }

    @Override
    public void onResponse(Response response) throws IOException {
        handler.post(new Runnable() {
            @Override
            public void run() {
                //UI
            }
        });
    }
});
    原文作者:MinuitZ
    原文地址: https://www.jianshu.com/p/4d5e7465a043
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞