1. 程式人生 > >Http請求-okhttp3基本用法

Http請求-okhttp3基本用法

# 簡介 HTTP是現代應用常用的一種交換資料和媒體的網路方式,高效地使用HTTP能讓資源載入更快,節省頻寬。OkHttp是一個高效的HTTP客戶端,它有以下預設特性: * 支援HTTP/2,允許所有同一個主機地址的請求共享同一個socket連線 * 連線池減少請求延時 * 透明的GZIP壓縮減少響應資料的大小 * 快取響應內容,避免一些完全重複的請求 原始碼:[https://github.com/square/okhttp](https://github.com/square/okhttp) 說明:OkHttp支援Android 2.3及以上版本Android平臺,對於Java, JDK1.7及以上。 當網路出現問題的時候OkHttp依然堅守自己的職責,它會自動恢復一般的連線問題,如果你的服務有多個IP地址,當第一個IP請求失敗時,OkHttp會交替嘗試你配置的其他IP,OkHttp使用現代TLS技術(SNI, ALPN)初始化新的連線,當握手失敗時會回退到TLS 1.0。 # 簡單使用 引入maven依賴 ``` xml ``` ## 請求方法 ### 同步請求 > 就是執行請求的操作是阻塞式,直到 HTTP 響應返回。它對應 OKHTTP 中的 execute 方法。 #### GET請求 ``` java /** * 同步get方式請求 * * @param url * @return * @throws IOException */ public static String doGet(String url) throws IOException { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .build(); try (Response response = client.newCall(request).execute()) { if (response.isSuccessful()) { return response.body().string(); } else { throw new IOException("Unexpected code " + response); } } } ``` #### POST請求 #### Json提交引數 ``` java /** * 同步post方式請求-json提交引數 * * @param url * @param json * @return * @throws IOException */ public static String doPost(String url, final String json) throws IOException { OkHttpClient client = new OkHttpClient(); RequestBody body = RequestBody.create(JSON, json); Request request = new Request.Builder() .url(url) .post(body) .build(); try (Response response = client.newCall(request).execute()) { if (response.isSuccessful()) { return response.body().string(); } else { throw new IOException("Unexpected code " + response); } } } ``` #### form表單提交引數 ``` java /** * 同步post方式請求-form表單提交引數 * * @param url * @param paramsMap * @return * @throws IOException */ public static String doPost(String