OKHttp(一)入門

OkHttp官網地址:http://square.github.io/okhttp/ 

OkHttp GitHub地址:https://github.com/square/okhttp 

OkHttp自我介紹: 

OkHttp是一款優秀的HTTP框架,它支持get請求和post請求,支持基於Http的文件上傳和下載,支持加載圖片,支持下載文件透明的GZIP壓縮,

支持響應緩存避免重複的網絡請求,支持使用連接池來降低響應延遲問題。

配置方法

<dependency>

<groupId>com.squareup.okhttp3<groupId>

<artifactId>okhttp<artifactId>

<version>3.2.0<version>

<dependency>

基本要求

Requests(請求)

每一個HTTP請求中都應該包含一個URL,一個GET或POST方法以及Header或其他參數,當然還可以含特定內容類型的數據流。

Responses(響應)

響應則包含一個回覆代碼(200代表成功,404代表未找到),Header和定製可選的body。

基本使用

在日常開發中最常用到的網絡請求就是GET和POST兩種請求方式。

HTTP GET

OkHttpClient client = new OkHttpClient();
String run(String url) throws IOException {
    Request request = new Request.Builder().url(url).build();
    Response response = client.newCall(request).execute();
    if (response.isSuccessful()) {
        return response.body().string();
    } else {
        throw new IOException("Unexpected code " + response);
    }
}

Request是OkHttp中訪問的請求,Builder是輔助類,Response即OkHttp中的響應。
Response類:

public boolean isSuccessful()
Returns true if the code is in [200..300), which means the request was successfully received, understood, and accepted.
response.body()返回ResponseBody類

可以方便的獲取string

public final String string() throws IOException
Returns the response as a string decoded with the charset of the Content-Type header. If that header is either absent or lacks a charset, this will attempt to decode the response body as UTF-8.
Throws:
IOException

當然也能獲取到流的形式:
public final InputStream byteStream()

HTTP POST

POST提交Json數據

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();
    f (response.isSuccessful()) {
        return response.body().string();
    } else {
        throw new IOException("Unexpected code " + response);
    }
}

使用Request的post方法來提交請求體RequestBody
POST提交鍵值對
OkHttp也可以通過POST方式把鍵值對數據傳送到服務器

OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
    RequestBody formBody = new FormEncodingBuilder()
    .add("platform", "android")
    .add("name", "bug")
    .add("subject", "XXXXXXXXXXXXXXX")
    .build();

    Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();

    Response response = client.newCall(request).execute();
    if (response.isSuccessful()) {
        return response.body().string();
    } else {
        throw new IOException("Unexpected code " + response);
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章