[译] 2024 年的 Android 网络 —— Retrofit 与 Kotlin 协程

在版本控制系统中隐藏 API 密钥(可选但推荐)

获取 API 密钥后,按照下述步骤将其在 VCS 中隐藏。

  • 将你的密钥添加到根目录下的 local.properties 文件中。
  • build.gradle 中用代码来访问密钥。
  • 之后在程序中通过 BuildConfig 就可以使用密钥了。

//In local.properties
tmdb_api_key = “xxxxxxxxxxxxxxxxxxxxxxxxxx”

//In build.gradle (Module: app)
buildTypes.each {
Properties properties = new Properties()
properties.load(project.rootProject.file(“local.properties”).newDataInputStream())
def tmdbApiKey = properties.getProperty(“tmdb_api_key”, “”)

it.buildConfigField ‘String’, “TMDB_API_KEY”, tmdbApiKey

it.resValue ‘string’, “api_key”, tmdbApiKey

}

//In your Constants File
var tmdbApiKey = BuildConfig.TMDB_API_KEY

设置项目

为了设置项目,我们首先会将所有必需的依赖项添加到 build.gradle (Module: app) 文件中:

// build.gradle(Module: app)
dependencies {

def moshiVersion=“1.8.0”
def retrofit2_version = “2.5.0”
def okhttp3_version = “3.12.0”
def kotlinCoroutineVersion = “1.0.1”
def picassoVersion = “2.71828”

//Moshi
implementation “com.squareup.moshi:moshi-kotlin: m o s h i V e r s i o n " k a p t " c o m . s q u a r e u p . m o s h i : m o s h i − k o t l i n − c o d e g e n : moshiVersion" kapt "com.squareup.moshi:moshi-kotlin-codegen: moshiVersion"kapt"com.squareup.moshi:moshikotlincodegen:moshiVersion”

//Retrofit2
implementation “com.squareup.retrofit2:retrofit: r e t r o f i t 2 v e r s i o n " i m p l e m e n t a t i o n " c o m . s q u a r e u p . r e t r o f i t 2 : c o n v e r t e r − m o s h i : retrofit2_version" implementation "com.squareup.retrofit2:converter-moshi: retrofit2version"implementation"com.squareup.retrofit2:convertermoshi:retrofit2_version”
implementation “com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2”

//Okhttp3
implementation “com.squareup.okhttp3:okhttp:$okhttp3_version”
implementation ‘com.squareup.okhttp3:logging-interceptor:3.11.0’

//Picasso for Image Loading
implementation (“com.squareup.picasso:picasso:$picassoVersion”){
exclude group: “com.android.support”
}

//Kotlin Coroutines
implementation “org.jetbrains.kotlinx:kotlinx-coroutines-android: k o t l i n C o r o u t i n e V e r s i o n " i m p l e m e n t a t i o n " o r g . j e t b r a i n s . k o t l i n x : k o t l i n x − c o r o u t i n e s − c o r e : kotlinCoroutineVersion" implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core: kotlinCoroutineVersion"implementation"org.jetbrains.kotlinx:kotlinxcoroutinescore:kotlinCoroutineVersion”

}

现在创建我们的 TmdbAPI 服务

//ApiFactory to create TMDB Api
object Apifactory{

//Creating Auth Interceptor to add api_key query in front of all the requests.
private val authInterceptor = Interceptor {chain->
val newUrl = chain.request().url()
.newBuilder()
.addQueryParameter(“api_key”, AppConstants.tmdbApiKey)
.build()

val newRequest = chain.request()
.newBuilder()
.url(newUrl)
.build()

chain.proceed(newRequest)
}

//OkhttpClient for building http request url
private val tmdbClient = OkHttpClient().newBuilder()
.addInterceptor(authInterceptor)
.build()

fun retrofit() : Retrofit = Retrofit.Builder()
.client(tmdbClient)
.baseUrl(“https://api.themoviedb.org/3/”)
.addConverterFactory(MoshiConverterFactory.create())
.addCallAdapterFactory(CoroutineCallAdapterFactory())
.build()

val tmdbApi : TmdbApi = retrofit().create(TmdbApi::class.java)

}

看一下我们在 ApiFactory.kt 文件中做了什么。

  • 首先,我们创建了一个用以给所有请求添加 api_key 参数的网络拦截器,名为 authInterceptor
  • 然后我们用 OkHttp 创建了一个网络客户端,并添加了 authInterceptor。
  • 接下来,我们用 Retrofit 将所有内容连接起来构建 Http 请求的构造器和处理器。此处我们加入了之前创建好的网络客户端、基础 URL、一个转换器和一个适配器工厂。 首先是 MoshiConverter,用以辅助 JSON 解析并将响应的 JSON 转化为 Kotlin 数据类,如有需要,可进行选择性解析。 第二个是 CoroutineCallAdaptor,它的类型是 Retorofit2 中的 CallAdapter.Factory,用于处理 Kotlin 协程中的 Deferred
  • 最后,我们只需将 TmdbApi 类(下节中创建) 的一个引用传入之前建好的 retrofit 类中就可以创建我们的 tmdbApi。

探索 Tmdb API

调用 /movie/popular 接口我们得到了如下响应。该响应中返回了 results,这是一个 movie 对象的数组。这正是我们关注的地方。

{
“page”: 1,
“total_results”: 19848,
“total_pages”: 993,
“results”: [
{
“vote_count”: 2109,
“id”: 297802,
“video”: false,
“vote_average”: 6.9,
“title”: “Aquaman”,
“popularity”: 497.334,
“poster_path”: “/5Kg76ldv7VxeX9YlcQXiowHgdX6.jpg”,
“original_language”: “en”,
“original_title”: “Aquaman”,
“genre_ids”: [
28,
14,
878,
12
],
“backdrop_path”: “/5A2bMlLfJrAfX9bqAibOL2gCruF.jpg”,
“adult”: false,
“overview”: “Arthur Curry learns that he is the heir to the underwater kingdom of Atlantis, and must step forward to lead his people and be a hero to the world.”,
“release_date”: “2018-12-07”
},
{
“vote_count”: 625,
“id”: 424783,
“video”: false,
“vote_average”: 6.6,
“title”: “Bumblebee”,
“popularity”: 316.098,
“poster_path”: “/fw02ONlDhrYjTSZV8XO6hhU3ds3.jpg”,
“original_language”: “en”,
“original_title”: “Bumblebee”,
“genre_ids”: [
28,
12,
878
],
“backdrop_path”: “/8bZ7guF94ZyCzi7MLHzXz6E5Lv8.jpg”,
“adult”: false,
“overview”: “On the run in the year 1987, Bumblebee finds refuge in a junkyard in a small Californian beach town. Charlie, on the cusp of turning 18 and trying to find her place in the world, discovers Bumblebee, battle-scarred and broken. When Charlie revives him, she quickly learns this is no ordinary yellow VW bug.”,
“release_date”: “2018-12-15”
}
]
}

因此现在我们可以根据该 JSON 创建我们的 Movie 数据类和 MovieResponse 类。

// Data Model for TMDB Movie item
data class TmdbMovie(
val id: Int,
val vote_average: Double,
val title: String,
val overview: String,
val adult: Boolean
)

// Data Model for the Response returned from the TMDB Api
data class TmdbMovieResponse(
val results: List
)

//A retrofit Network Interface for the Api
interface TmdbApi{

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数Android工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
img
img
img
img
img
img
img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新

如果你觉得这些内容对你有帮助,可以添加V获取:vip204888 (备注Android)
img

最后

其实要轻松掌握很简单,要点就两个:

  1. 找到一套好的视频资料,紧跟大牛梳理好的知识框架进行学习。
  2. 多练。 (视频优势是互动感强,容易集中注意力)

你不需要是天才,也不需要具备强悍的天赋,只要做到这两点,短期内成功的概率是非常高的。

对于很多初中级Android工程师而言,想要提升技能,往往是自己摸索成长,不成体系的学习效果低效漫长且无助。

阿里P7Android高级教程

下面资料部分截图,诚意满满:特别适合有3-5年开发经验的Android程序员们学习。

附送高清脑图,高清知识点讲解教程,以及一些面试真题及答案解析。送给需要的提升技术、近期面试跳槽、自身职业规划迷茫的朋友们。

Android核心高级技术PDF资料,BAT大厂面试真题解析;

一个人可以走的很快,但一群人才能走的更远。不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎扫码加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
img
业规划迷茫的朋友们。

Android核心高级技术PDF资料,BAT大厂面试真题解析;
[外链图片转存中…(img-afP3SX6V-1712784240125)]

一个人可以走的很快,但一群人才能走的更远。不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎扫码加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
[外链图片转存中…(img-vQLi27Ki-1712784240126)]

  • 14
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值