前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【OkHttp】Android 项目导入 OkHttp ( 配置依赖 | 配置 networkSecurityConfig | 配置 ViewBinding | 代码示例 )

【OkHttp】Android 项目导入 OkHttp ( 配置依赖 | 配置 networkSecurityConfig | 配置 ViewBinding | 代码示例 )

作者头像
韩曙亮
发布2023-03-29 14:18:23
1.9K0
发布2023-03-29 14:18:23
举报
文章被收录于专栏:韩曙亮的移动开发专栏

OkHttp 系列文章目录

【OkHttp】OkHttp 简介 ( OkHttp 框架特性 | Http 版本简介 )

【OkHttp】Android 项目导入 OkHttp ( 配置依赖 | 配置 networkSecurityConfig | 配置 ViewBinding | 代码示例 )


文章目录


前言

在上一篇博客 【OkHttp】OkHttp 简介 ( OkHttp 框架特性 | Http 版本简介 ) 中简要介绍了 OkHttp 及 Http , 本博客开始介绍 OkHttp 框架的使用 ;


一、OkHttp 导入流程


1、配置依赖

导入 OkHttp3 依赖库 : 在 Module 下的 build.gradle 配置文件中的 dependencies 节点 , 进行如下配置 ;

代码语言:javascript
复制
implementation 'com.squareup.okhttp3:okhttp:3.14.+'

2、配置 networkSecurityConfig ( 兼容 HTTP )

配置 HTTP : Android

9.0

之后不允许使用 HTTP, 只能使用 HTTPS , 如果要使用 HTTP , 必须在 application 节点的 android:networkSecurityConfig 属性中配置 <network-security-config> 节点的 XML 配置文件 ;

代码语言:javascript
复制
<?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 属性 ;

代码语言:javascript
复制
<?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" />

    <application
        android: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 节点 , 进行如下配置 ;

代码语言:javascript
复制
android.buildFeatures.viewBinding = true

2、Activity 初始化 ViewBinding

Activity 初始化 ViewBinding :

① 声明视图绑定成员 : 定义 ActivityMainBinding 成员变量 , ActivityMainBinding 是 activity_main 布局映射出来的类 ;

代码语言:javascript
复制
    /**
     * ViewBinding 类
     * activity_main 布局映射出来的类
     * 该类主要作用是封装组件的获取
     */
    ActivityMainBinding binding;

② 初始化视图绑定类 : 在 onCreate 方法中初始化 ActivityMainBinding 成员变量 ;

代码语言:javascript
复制
binding = ActivityMainBinding.inflate(getLayoutInflater());

③ 设置 Activity 布局显示 :

代码语言:javascript
复制
setContentView(binding.getRoot());

三、OkHttp 同步 Get 请求


OkHttp 同步 Get 请求步骤 :

① 初始化 OkHttp 类 :

代码语言:javascript
复制
    /**
     * OkHttp 客户端
     * 注意 : 该类型对象较大, 尽量在应用中创建较少的该类型对象
     * 推荐使用单例
     */
    OkHttpClient mOkHttpClient;
	
	// 初始化操作 
	mOkHttpClient = new OkHttpClient();

② 构造 Request 请求对象 :

代码语言:javascript
复制
        // Request 中封装了请求相关信息
        Request request = new Request.Builder()
                .url("https://www.baidu.com")   // 设置请求地址
                .get()                          // 使用 Get 方法
                .build();

③ 同步 Get 请求 : 网络请求事件必须放在线程中 ;

代码语言:javascript
复制
// 同步 Get 请求
new Thread(new Runnable() {
    @Override
    public 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 代码

代码语言:javascript
复制
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;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        mOkHttpClient = new OkHttpClient();

        binding.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public 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() {
            @Override
            public 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 构建脚本

代码语言:javascript
复制
plugins {
    id 'com.android.application'
}

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.example.okhttp"
        minSdkVersion 21
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility 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 清单文件

代码语言:javascript
复制
<?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" />

    <application
        android: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 目录下 ;

代码语言:javascript
复制
<?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 信息 ;

代码语言:javascript
复制
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&amp;tpl=mn&amp;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>&copy;2017&nbsp;Baidu&nbsp;<a href=http://www.baidu.com/duty/>使用百度前必读</a>&nbsp; <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a>&nbsp;京ICP证030173号&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>

五、博客资源

GitHub : https://github.com/han1202012/OkHttp

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-06-21,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 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、执行结果
                      • 五、博客资源
                      领券
                      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档