【OkHttp】Android 项目导入 OkHttp ( 配置依赖 | 配置 networkSecurityConfig | 配置 ViewBinding | 代码示例 )
OkHttp 系列文章目錄
【OkHttp】OkHttp 簡介 ( OkHttp 框架特性 | Http 版本簡介 )
【OkHttp】Android 項目導入 OkHttp ( 配置依賴 | 配置 networkSecurityConfig | 配置 ViewBinding | 代碼示例 )
文章目錄
- OkHttp 系列文章目錄
- 前言
- 一、OkHttp 導入流程
- 1、配置依賴
- 2、配置 networkSecurityConfig ( 兼容 HTTP )
- 二、ViewBinding 配置
- 1、啟用 ViewBinding
- 2、Activity 初始化 ViewBinding
- 三、OkHttp 同步 Get 請求
- 四、代碼示例
- 1、MainActivity 代碼
- 2、build.gradle 構建腳本
- 3、AndroidManifest.xml 清單文件
- 4、network_security_config.xml 配置文件
- 5、執行結果
- 五、博客資源
前言
在上一篇博客 【OkHttp】OkHttp 簡介 ( OkHttp 框架特性 | Http 版本簡介 ) 中簡要介紹了 OkHttp 及 Http , 本博客開始介紹 OkHttp 框架的使用 ;
一、OkHttp 導入流程
1、配置依賴
導入 OkHttp3 依賴庫 : 在 Module 下的 build.gradle 配置文件中的 dependencies 節點 , 進行如下配置 ;
implementation 'com.squareup.okhttp3:okhttp:3.14.+'2、配置 networkSecurityConfig ( 兼容 HTTP )
配置 HTTP : Android 9.09.09.0 之后不允許使用 HTTP, 只能使用 HTTPS , 如果要使用 HTTP , 必須在 application 節點的 android:networkSecurityConfig 屬性中配置 <network-security-config> 節點的 XML 配置文件 ;
<?xml version="1.0" encoding="utf-8"?> <network-security-config><!-- Android 9.0 之后不允許使用 HTTP, 只能使用 HTTPS,如果要使用 HTTP , 必須在 application 節點的 android:networkSecurityConfig 屬性中配置本文件 --><base-config cleartextTrafficPermitted="true" /> </network-security-config>清單文件配置 : 關注兩個點 ,① 配置 android.permission.INTERNET 網絡權限 , ② 配置 application 節點的 android:networkSecurityConfig 屬性 ;
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.example.okhttp"><uses-permission android:name="android.permission.INTERNET" /><applicationandroid:networkSecurityConfig="@xml/network_security_config"android:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/Theme.OkHttp"><activity android:name=".MainActivity"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application></manifest>二、ViewBinding 配置
1、啟用 ViewBinding
啟用 ViewBinding : 在 Module 下的 build.gradle 配置文件中的 android 節點 , 進行如下配置 ;
android.buildFeatures.viewBinding = true2、Activity 初始化 ViewBinding
Activity 初始化 ViewBinding :
① 聲明視圖綁定成員 : 定義 ActivityMainBinding 成員變量 , ActivityMainBinding 是 activity_main 布局映射出來的類 ;
/*** ViewBinding 類* activity_main 布局映射出來的類* 該類主要作用是封裝組件的獲取*/ActivityMainBinding binding;② 初始化視圖綁定類 : 在 onCreate 方法中初始化 ActivityMainBinding 成員變量 ;
binding = ActivityMainBinding.inflate(getLayoutInflater());③ 設置 Activity 布局顯示 :
setContentView(binding.getRoot());三、OkHttp 同步 Get 請求
OkHttp 同步 Get 請求步驟 :
① 初始化 OkHttp 類 :
/*** OkHttp 客戶端* 注意 : 該類型對象較大, 盡量在應用中創建較少的該類型對象* 推薦使用單例*/OkHttpClient mOkHttpClient;// 初始化操作 mOkHttpClient = new OkHttpClient();② 構造 Request 請求對象 :
// Request 中封裝了請求相關信息Request request = new Request.Builder().url("https://www.baidu.com") // 設置請求地址.get() // 使用 Get 方法.build();③ 同步 Get 請求 : 網絡請求事件必須放在線程中 ;
// 同步 Get 請求 new Thread(new Runnable() {@Overridepublic void run() {Response response = null;try {response = mOkHttpClient.newCall(request).execute();} catch (IOException e) {e.printStackTrace();}String result = null;try {result = response.body().string();} catch (IOException e) {e.printStackTrace();}Log.i(TAG, "result : " + result);} }).start();四、代碼示例
1、MainActivity 代碼
package com.example.okhttp;import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle; import android.util.Log; import android.view.View;import com.example.okhttp.databinding.ActivityMainBinding;import java.io.IOException;import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response;public class MainActivity extends AppCompatActivity {private static final String TAG = "MainActivity";/*** ViewBinding 類* activity_main 布局映射出來的類* 該類主要作用是封裝組件的獲取*/ActivityMainBinding binding;/*** OkHttp 客戶端* 注意 : 該類型對象較大, 盡量在應用中創建較少的該類型對象* 推薦使用單例*/OkHttpClient mOkHttpClient;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);binding = ActivityMainBinding.inflate(getLayoutInflater());setContentView(binding.getRoot());mOkHttpClient = new OkHttpClient();binding.button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {httpGet();}});}/*** OkHttp Get 請求*/private void httpGet() {// Request 中封裝了請求相關信息Request request = new Request.Builder().url("https://www.baidu.com") // 設置請求地址.get() // 使用 Get 方法.build();// 同步 Get 請求new Thread(new Runnable() {@Overridepublic void run() {Response response = null;try {response = mOkHttpClient.newCall(request).execute();} catch (IOException e) {e.printStackTrace();}String result = null;try {result = response.body().string();} catch (IOException e) {e.printStackTrace();}Log.i(TAG, "result : " + result);}}).start();} }
2、build.gradle 構建腳本
plugins {id 'com.android.application' }android {compileSdkVersion 30buildToolsVersion "30.0.3"defaultConfig {applicationId "com.example.okhttp"minSdkVersion 21targetSdkVersion 30versionCode 1versionName "1.0"testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"}buildTypes {release {minifyEnabled falseproguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'}}compileOptions {sourceCompatibility JavaVersion.VERSION_1_8targetCompatibility JavaVersion.VERSION_1_8}android.buildFeatures.viewBinding = true }dependencies {implementation 'androidx.appcompat:appcompat:1.3.0'implementation 'com.google.android.material:material:1.3.0'implementation 'androidx.constraintlayout:constraintlayout:2.0.4'testImplementation 'junit:junit:4.+'androidTestImplementation 'androidx.test.ext:junit:1.1.2'androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'implementation 'com.squareup.okhttp3:okhttp:3.14.+' }
3、AndroidManifest.xml 清單文件
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.example.okhttp"><uses-permission android:name="android.permission.INTERNET" /><applicationandroid:networkSecurityConfig="@xml/network_security_config"android:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/Theme.OkHttp"><activity android:name=".MainActivity"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application></manifest>
4、network_security_config.xml 配置文件
HTTP 兼容配置文件 : src/main/res/xml 目錄下 ;
<?xml version="1.0" encoding="utf-8"?> <network-security-config><!-- Android 9.0 之后不允許使用 HTTP, 只能使用 HTTPS,如果要使用 HTTP , 必須在 application 節點的 android:networkSecurityConfig 屬性中配置本文件 --><base-config cleartextTrafficPermitted="true" /> </network-security-config>5、執行結果
使用 Get 方法請求 https://www.baidu.com 地址 , 獲取的是百度首頁 html 信息 ;
I/MainActivity: result : <!DOCTYPE html><!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus=autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn" autofocus></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>新聞</a> <a href=https://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>地圖</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>視頻</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>貼吧</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>登錄</a> </noscript> <script>document.write('<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">登錄</a>');</script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">更多產品</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>關于百度</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>©2017 Baidu <a href=http://www.baidu.com/duty/>使用百度前必讀</a> <a href=http://jianyi.baidu.com/ class=cp-feedback>意見反饋</a> 京ICP證030173號 <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>五、博客資源
GitHub : https://github.com/han1202012/OkHttp
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的【OkHttp】Android 项目导入 OkHttp ( 配置依赖 | 配置 networkSecurityConfig | 配置 ViewBinding | 代码示例 )的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【OkHttp】OkHttp 简介 (
- 下一篇: 【计算机网络】HTTP 与 HTTPS