1.OkHttp主頁項目github地址:
https://github.com/square/okhttp
2.編寫網絡請求代碼前的一些小步驟:
1.編輯app/build.gradle文件,在dependencies閉包中添加依賴
implementation'com.squareup.okhttp3:okhttp:3.14.2'

2.在AndroidManifest.xml文件中添加訪問網絡的權限:
<uses-permission android:name="android.permission.INTERNET" />

3.在app目錄的build.gradle目錄下添加添加對java8支持
方式1:
compileOptions{
? sourceCompatibility JavaVersion.VERSION_1_8
? targetCompatibility JavaVersion.VERSION_1_8
}方式2:
compileOptions {
???? targetCompatibility = "8"
???? sourceCompatibility = "8"
}方式3
compileOptions {
????? sourceCompatibility 1.8
????? targetCompatibility 1.8
}



4.(兼容Android9.0)必須更改網絡安全配置(如果請求的網絡是https就無需步驟4和步驟5)
第一步:
????? 在res文件夾下創(chuàng)建一個xml文件夾,
????? 然后創(chuàng)建一個network_security_config.xml文件,
????? 文件內容如下:?<?xml version="1.0" encoding="utf-8"?>
????? <network-security-config>
????? ? ? ? ?? <base-config cleartextTrafficPermitted="true" />
????? </network-security-config>第二步:
????? 在AndroidManifest.xml文件下的application標簽增加以下屬性??
????? android:networkSecurityConfig="@xml/network_security_config"


3簡單的Get請求的一些常規(guī)步驟(此處僅以小Demo的形式作為驗證集成okhttpd集成是否成功,此處并沒做深入分析)
一:Get請求
步驟1:創(chuàng)建Request對象Request request = new Request.Builder()
????????????????????????????? .url("http://www.baidu.com")//通過url()方法來設置目標網絡地址
????????????????????????????? .build();步驟2:創(chuàng)建OkHttpClient對象
OkHttpClient client = new OkHttpClient();
步驟 3:使用okhttpclient對象調用newCall()方法來創(chuàng)建Call對象,調用execute()方法發(fā)送請求并獲取服務器返回的數據(Responce對象)
Response responce = client.newCall(request).execute();
步驟4:通過responce.body()獲取響應體,進而再調用其它方法獲取返回的具體內容(此處以String為例)
String responceData = responce.body().string();
5.get請求
5-1:GET同步請求
private void loadDataSync(){
??????????? new Thread(new Runnable() {
??????????? @Override
???????????? public void run() {
???????????? String url="http://www.baidu.com";
??????????? //構建一個網絡請求
???????????? Request request = new Request.Builder().get().url(url).build();
???????????? try {
????????????????????? OkHttpClient okHttpClient = new OkHttpClient();
????????????????????? //執(zhí)行網絡請求獲取網絡響應結果
?????????????????????? Response response = okHttpClient.newCall(request).execute();
??????????????????? //獲取響應體字符串
??????????????????? String string = response.body().string();
? ? ? ? ? ????????? Log.d(TAG,"loadDataSync"+string);
?????????????????? } catch (IOException e) {
?????????????????????????????? e.printStackTrace();
????????????????? }
????????? ? ? }
????????? }).start();
????? }

運行結果如下圖所示:
