01.OkHttp基本用法

目錄介紹

  • 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的流程圖

  • 首先放一張完整流程圖(看不懂沒關係,慢慢往後看):
    • image
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章