欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

01.OkHttp基本用法

程序员文章站 2022-07-13 10:58:42
...

目录介绍

  • 01.OkHttp简单介绍
  • 02.OkHttp简单使用
  • 03.OkHttp的流程图

01.OkHttp简单介绍

  • 1.支持HTTP2/SPDY
  • 2.socket自动选择最好路线,并支持自动重连
  • 3.拥有自动维护的socket连接池,减少握手次数
  • 4.拥有队列线程池,轻松写并发
  • 5.拥有Interceptors轻松处理请求与响应(比如透明GZIP压缩)基于Headers的缓存策略

02.OkHttp简单使用

2.1 Get请求

  • get同步请求
    String url = "www.baidu.com/index";
    OkHttpClient okHttpClient = new OkHttpClient();
    Request request = new Request.Builder()
            .url(url)
            .build();
    
    Response response;
    try {
        response = okHttpClient.newCall(request).execute();
        String body = response.body().string();
        Log.d("body---yc---",body);
    } catch (IOException e) {
        e.printStackTrace();
    }
    
  • get异步请求
    String url = "www.baidu.com/index";
    OkHttpClient okHttpClient = new OkHttpClient();
    Request request = new Request.Builder()
            .url(url)
            .build();
    okHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(@NonNull Call call, @NonNull IOException e) {
    
        }
    
        @Override
        public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
            String body = response.body().string();
            Log.d("body---yc---",body);
        }
    });
    

2.2 Post请求

  • Post同步请求
    String url = "www.baidu.com/index";
    String json = "{\"page\":1,\"name\":\"yc\",\"age\":26}";
    MediaType type = MediaType.parse("application/json; charset=utf-8");
    OkHttpClient client = new OkHttpClient();
    RequestBody body = RequestBody.create(type, json);
    Request request = new Request.Builder()
            .url(url)
            .post(body)
            .build();
    Response response = null;
    try {
        response = client.newCall(request).execute();
        String string = response.body().string();
    } catch (IOException e) {
        e.printStackTrace();
    }
    
  • Post异步请求
    String url = "www.baidu.com/index";
    String json = "{\"page\":1,\"name\":\"yc\",\"age\":26}";
    MediaType type = MediaType.parse("application/json; charset=utf-8");
    OkHttpClient client = new OkHttpClient();
    RequestBody body = RequestBody.create(type, json);
    Request request = new Request.Builder()
            .url(url)
            .post(body)
            .build();
    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(@NonNull Call call, @NonNull IOException e) {
    
        }
    
        @Override
        public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
            String string = response.body().string();
        }
    });
    

03.OkHttp的流程图

  • 首先放一张完整流程图(看不懂没关系,慢慢往后看):
    • 01.OkHttp基本用法
相关标签: OkHttp