掃二維碼與項目經(jīng)理溝通
我們在微信上24小時期待你的聲音
解答本文疑問/技術(shù)咨詢/運營咨詢/技術(shù)建議/互聯(lián)網(wǎng)交流
現(xiàn)在開源的市場上,能網(wǎng)絡(luò)請求的工具非常的多,比如 HttpURLConnection 、Apache HttpClient、okHttp、Retrofit 等等。

成都創(chuàng)新互聯(lián)公司專業(yè)為企業(yè)提供萬榮網(wǎng)站建設(shè)、萬榮做網(wǎng)站、萬榮網(wǎng)站設(shè)計、萬榮網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計與制作、萬榮企業(yè)網(wǎng)站模板建站服務(wù),10多年萬榮做網(wǎng)站經(jīng)驗,不只是建網(wǎng)站,更提供有價值的思路和整體網(wǎng)絡(luò)服務(wù)。
雖然可選擇的工具很多,但是作為一名開發(fā)者,我們希望在寫代碼的時候,能夠輕松地調(diào)試我們應(yīng)用程序的網(wǎng)絡(luò)通信,選擇適合的工具至關(guān)重要!
就目前我們所熟悉的,其中 Apache HttpClient 因其高效的性能、豐富的 api,在開源項目中使用非常廣泛,Android 系統(tǒng)最早默認的網(wǎng)絡(luò)請求工具也是使用 Apache HttpClient,但因為兼容性問題,Android 后期的版本中谷歌不愿意維護相關(guān)包,改而使用 okHttp。
現(xiàn)在 Android 系統(tǒng)中的網(wǎng)絡(luò)請求框架,基本都是 okhttp 和 Retrofit 一統(tǒng)天下,兩者其實都是 square 公司出品的,不同的地方在于 Retrofit 是基于 OkHttp 封裝的一套 RESTful 網(wǎng)絡(luò)請求框架,使用方面更加靈活,屬于后起之秀!
既然大家都覺得 OkHttp 好用,今天我們就一起來認識一下它!
來著網(wǎng)上對于 OkHttp 相關(guān)的介紹如下!
OkHttp 是 Square 公司基于 Java 和 Android 程序,封裝的一個高性能 http 網(wǎng)絡(luò)請求客戶端,并且對外開源,它的設(shè)計初衷是為了更快地加載資源并節(jié)省帶寬。
以下是使用 OkHttp 的主要優(yōu)勢:
目前 OkHttp 在開源項目中被廣泛使用,同時也是 Retrofit、Picasso 等庫的核心庫。
既然這么厲害,在網(wǎng)絡(luò)通信中我們?nèi)绾问褂媚兀覀円黄饋韺W(xué)習(xí)一下!
在使用之前,我們需要先導(dǎo)入okhttp?依賴包,不同的版本號,相關(guān) api 稍有區(qū)別,本次介紹的 api 操作基于3.14.9版本號。
com.squareup.okhttp3
okhttp
3.14.9
okhttp?發(fā)起get同步請求非常的簡單,只需要幾行代碼就可以搞定。
案例如下!
String url = "https://www.baidu.com/";
OkHttpClient client = new OkHttpClient();
// 配置GET請求
Request request = new Request.Builder()
.url(url)
.get()
.build();
// 發(fā)起同步請求
try (Response response = client.newCall(request).execute()){
// 打印返回結(jié)果
System.out.println(response.body().string());
} catch (Exception e) {
e.printStackTrace();
}
okhttp?發(fā)起post表單格式的數(shù)據(jù)提交,同步請求編程也非常的簡單,只需要幾行代碼就可以搞定。
案例如下!
String url = "https://www.baidu.com/";
OkHttpClient client = new OkHttpClient();
// 配置 POST + FORM 格式數(shù)據(jù)請求
RequestBody body = new FormBody.Builder()
.add("userName", "zhangsan")
.add("userPwd", "123456")
.build();
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
// 發(fā)起同步請求
try (Response response = client.newCall(request).execute()){
// 打印返回結(jié)果
System.out.println(response.body().string());
} catch (Exception e) {
e.printStackTrace();
}
如果在發(fā)起表單請求的時候,還需要上傳文件,該如何實現(xiàn)呢?
案例如下!
String url = "https://www.baidu.com/";
OkHttpClient client = new OkHttpClient();
// 要上傳的文件
File file = new File("/doc/Downloads/429545913565844e9b26f97dbb57a1c3.jpeg");
RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpg"), file);
// 表單 + 文件數(shù)據(jù)提交
RequestBody multipartBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("userName", "zhangsan")
.addFormDataPart("userPwd", "123456")
.addFormDataPart("userFile", "00.png", fileBody)
.build();
Request request = new Request.Builder()
.url(url)
.post(multipartBody)
.build();
// 發(fā)起同步請求
try (Response response = client.newCall(request).execute()){
// 打印返回結(jié)果
System.out.println(response.body().string());
} catch (Exception e) {
e.printStackTrace();
}
okhttp?發(fā)起post? + json格式的數(shù)據(jù)提交,同步請求編程也很簡單。
案例如下!
MediaType contentType = MediaType.get("application/json; charset=utf-8");
String url = "https://www.baidu.com/";
String json = "{}";
OkHttpClient client = new OkHttpClient();
// 配置 POST + JSON 請求
RequestBody body = RequestBody.create(contentType, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
// 發(fā)起同步請求
try (Response response = client.newCall(request).execute()){
// 打印返回結(jié)果
System.out.println(response.body().string());
} catch (Exception e) {
e.printStackTrace();
}
文件下載,通常是get方式請求,只需要在響應(yīng)端使用字節(jié)流接受數(shù)據(jù)即可!
案例如下!
public static void main(String[] args) {
//目標(biāo)存儲文件
String targetFile = "/doc/Downloads/1.png";
//需要下載的原始文件
String url = "https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png";
OkHttpClient client = new OkHttpClient();
// 配置GET請求
Request request = new Request.Builder()
.url(url)
.build();
// 發(fā)起同步請求
try (Response response = client.newCall(request).execute()){
// 獲取文件字節(jié)流
byte[] stream = response.body().bytes();
// 寫入目標(biāo)文件
writeFile(targetFile, stream);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 寫入目標(biāo)文件
* @param targetFile
* @param stream
* @throws IOException
*/
private static void writeFile(String targetFile, byte[] stream) throws IOException {
String filePath = StringUtils.substringBeforeLast(targetFile, "/");
Path folderPath = Paths.get(filePath);
if(!Files.exists(folderPath)){
Files.createDirectories(folderPath);
}
Path targetFilePath = Paths.get(targetFile);
if(!Files.exists(targetFilePath)){
Files.write(targetFilePath, stream, StandardOpenOption.CREATE);
}
}
在實際的項目開發(fā)中,有的接口需要使用put?或者delete方式請求,應(yīng)該如何處理呢?
put方式請求,案例如下!
// 只需要在 Request 配置類中,換成 put 方式即可
Request request = new Request.Builder()
.url(url)
.put(body)
.build();
同樣的,delete方式請求也類似,案例如下!
// 只需要在 Request 配置中,換成 delete 方式即可
Request request = new Request.Builder()
.url(url)
.delete(body)
.build();
大部分的時候,基于安全的考慮,很多時候我們需要把相關(guān)的鑒權(quán)參數(shù)放在請求頭部,應(yīng)該如何處理呢?
以post? + json格式請求為例,添加頭部請求參數(shù),案例如下!
MediaType contentType = MediaType.get("application/json; charset=utf-8");
String url = "https://www.baidu.com/";
String json = "{}";
OkHttpClient client = new OkHttpClient();
// 配置 header 頭部請求參數(shù)
Headers headers = new Headers.Builder()
.add("token", "11111-22222-333")
.build();
// 配置 POST + JSON 請求
RequestBody body = RequestBody.create(contentType, json);
Request request = new Request.Builder()
.url(url)
.headers(headers)
.post(body)
.build();
// 發(fā)起同步請求
try (Response response = client.newCall(request).execute()){
// 打印返回結(jié)果
System.out.println(response.body().string());
} catch (Exception e) {
e.printStackTrace();
}
在上文中我們介紹的都是同步請求,在最開始我們也說到 OkHttp 不僅支持同步調(diào)用,也異步調(diào)用,那么如何進行異步請求編程呢?
其實操作很簡單,案例如下!
String url = "https://www.baidu.com/";
OkHttpClient client = new OkHttpClient().newBuilder().build();
Request request = new Request.Builder()
.url(url)
.get()
.build();
// 發(fā)起異步請求
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
System.out.println("請求異常 + " + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
System.out.println("請求完成,返回結(jié)果:" + response.body().string());
}
});
以上就是小編針對 OkHttp 在使用上,做了一次簡單的內(nèi)容總結(jié),整體下來,從使用上來講,api 的操作確實比 Apache HttpClient 要簡單很多。
關(guān)于 OkHttp 的內(nèi)容其實還有很多,比如請求參數(shù)的全局配置、全局攔截器、websocket 等功能。

我們在微信上24小時期待你的聲音
解答本文疑問/技術(shù)咨詢/運營咨詢/技術(shù)建議/互聯(lián)網(wǎng)交流