OkHttp3基礎篇:Home

官方用一句話進行了介紹:

An HTTP & HTTP/2 client for Android and Java applications.

一、概述

HTTP 是互聯網上應用最為廣泛的一種網絡協議,可用于傳輸數據和媒體
高效使用HTTP不僅讓內容加載更快,且節省帶寬

對HTTP 不熟可以看之前的一篇文章:HTTP,請求消息,響應消息,Cookie(詳細總結)

  • OkHttp是從設計之初就是一款高效的 HTTP client

  • HTTP/2 允許同一 host 的所有請求共享 socket

  • 連接池降低了請求延遲 (if HTTP/2 isn’t available)

  • GZIP 縮減了下載的大小

  • 響應緩存完全避免網絡重復請求

  • OkHttp 會確保網絡的連接,它會悄悄地恢復一些常見的連接問題

  • 如果你的 service 有多個IP地址且第一個連接失敗,OkHttp將嘗試備用地址。

  • This is necessary for IPv4+IPv6 and for services hosted in redundant data centers.

  • OkHttp initiates new connections with modern TLS features (SNI, ALPN), and falls back to TLS 1.0 if the handshake fails.

  • OkHttp 的易用性

  • Its request/response API is designed with fluent builders and immutability.

  • 它同時支持同步阻塞調用和回調的異步調用

OkHttp支持Android 2.3及以上。對于Java,最低要求是1.7

二、使用例子

1. GET A URL

下面這個程序下載一個URL,并以字符串打印出其內容:

// 關鍵代碼
OkHttpClient client = new OkHttpClient();

String run(String url) throws IOException { 
    Request request = new Request.Builder() 
          .url(url) 
          .build(); 

    Response response = client.newCall(request).execute(); 
    return response.body().string();
}

// 完整代碼
package okhttp3.guide;

import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class GetExample {
  OkHttpClient client = new OkHttpClient();

  String run(String url) throws IOException {
    Request request = new Request.Builder()
        .url(url)
        .build();

    Response response = client.newCall(request).execute();
    return response.body().string();
  }

  public static void main(String[] args) throws IOException {
    GetExample example = new GetExample();
    String response = example.run("https://raw.github.com/square/okhttp/master/README.md");
    System.out.println(response);
  }
}

2. POST TO A SERVER

提交數據到服務端

// 關鍵代碼
public static final MediaType JSON
    = MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(JSON, json);
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  Response response = client.newCall(request).execute();
  return response.body().string();
}

// 完整代碼
package okhttp3.guide;

import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PostExample {
  public static final MediaType JSON
      = MediaType.parse("application/json; charset=utf-8");

  OkHttpClient client = new OkHttpClient();

  String post(String url, String json) throws IOException {
    RequestBody body = RequestBody.create(JSON, json);
    Request request = new Request.Builder()
        .url(url)
        .post(body)
        .build();
    Response response = client.newCall(request).execute();
    return response.body().string();
  }

  String bowlingJson(String player1, String player2) {
    return "{'winCondition':'HIGH_SCORE',"
        + "'name':'Bowling',"
        + "'round':4,"
        + "'lastSaved':1367702411696,"
        + "'dateStarted':1367702378785,"
        + "'players':["
        + "{'name':'" + player1 + "','history':[10,8,6,7,8],'color':-13388315,'total':39},"
        + "{'name':'" + player2 + "','history':[6,10,5,10,10],'color':-48060,'total':41}"
        + "]}";
  }

  public static void main(String[] args) throws IOException {
    PostExample example = new PostExample();
    String json = example.bowlingJson("Jesse", "Jake");
    String response = example.post("http://www.roundsapp.com/post", json);
    System.out.println(response);
  }
}

三、ja包下載或引用

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.2.0</version>
</dependency>
  • GRADLE
    compile 'com.squareup.okhttp3:okhttp:3.2.0'

參考文章:
[1] 官方原文:OkHttp

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容