新闻详情

新闻详情

首页 / 资讯中心 / 详情

网络 - Ktor(Retrofit 迁移版)

发布时间:2026/11/13 21:54:43来源:尧图网络
网络 - Ktor(Retrofit 迁移版)
一、概念二、添加依赖最新版本[versions] ktor 3.6.0 [libraries] ktor-core { module io.ktor:ktor-client-core, version.ref ktor } #核心库 ktor-okhttp { module io.ktor:ktor-client-okhttp, version.ref ktor } #Android用OkHttp ktor-negotiation { module io.ktor:ktor-client-content-negotiation, version.ref ktor } #内容协商 ktor-serialization { module io.ktor:ktor-serialization-kotlinx-json, version.ref ktor } #序列化 ktor-logging { module io.ktor:ktor-client-logging, version.ref ktor } #日志三、客户端迁移直接复用 OkHttp 设置只需要将 Retrofit 配置的替换掉。object KtorClient { // Json解析 private val json by lazy { Json { prettyPrint true // isLenient true //宽松解析单引号、松散JSON ignoreUnknownKeys true // 忽略接口返回的多余字段服务端新增字段不会导致崩溃容错升级 } } // OkHttp private val okHttp by lazy { OkHttpClient.Builder().build() } // Ktor private val ktor by lazy { HttpClient(OkHttp) { // 内容协商 install(ContentNegotiation) { json(json) // Json解析 } // BaseUrl install(DefaultRequest) { url() } // 引擎 engine { preconfigured okHttp // 用okhttp } } } // ApiService val apiService by lazy { ApiService(ktor) } }四、网络请求迁移从「声明式注解」变成「显式函数调用」。RetrofitKtorGET / POST / PUT / DELETEclient.get() / client.post() / client.put() / client.delete()PathURL 字符串拼接users/$idQueryparameter(key, value)QueryMapparameter()逐个调用或遍历 MapBodysetBody(obj)Headerheader(name, value)Headersheader()多次调用FormUrlEncodedFieldsetBody(FormDataContent(...))或submitForm()MultipartPartsetBody(MultiPartFormDataContent(...))Url直接传完整 URLStreamingprepareGet().execute { }流式读取class ApiService( private val client: HttpClient ) { // 请求方法 }4.1 GET// Retrofit GET(users) suspend fun getUsers(): ListUser // Ktor suspend fun getUsers(): ListUser client.get(users).body()4.2 Path 参数// Retrofit GET(search) suspend fun search( Query(keyword) keyword: String, Query(page) page: Int ): ListResult // Ktor suspend fun search(keyword: String, page: Int): ListResult client.get(search) { parameter(keyword, keyword) parameter(page, page) }.body()4.3 Query 参数// Retrofit GET(search) suspend fun search( Query(keyword) keyword: String, Query(page) page: Int ): ListResult // Ktor suspend fun search(keyword: String, page: Int): ListResult client.get(search) { parameter(keyword, keyword) parameter(page, page) }.body()4.4 POST Body// Retrofit POST(users) suspend fun createUser(Body user: User): User // Ktor suspend fun createUser(user: User): User client.post(users) { contentType(ContentType.Application.Json) setBody(user) }.body()4.5 Header// Retrofit GET(profile) suspend fun getProfile(Header(Authorization) token: String): Profile // Ktor suspend fun getProfile(token: String): Profile client.get(profile) { header(Authorization, token) }.body()4.6 固定 HeaderHeaders// Retrofit Headers(X-Client: android, Accept: application/json) GET(config) suspend fun getConfig(): Config // Ktor suspend fun getConfig(): Config client.get(config) { header(X-Client, android) header(Accept, application/json) }.body()4.7 表单提交FormUrlEncoded// Retrofit FormUrlEncoded POST(login) suspend fun login( Field(username) username: String, Field(password) password: String ): LoginResult // Ktor import io.ktor.client.request.forms.* suspend fun login(username: String, password: String): LoginResult client.submitForm( url login, formParameters parameters { append(username, username) append(password, password) } ).body() // 或者用 setBody suspend fun login(username: String, password: String): LoginResult client.post(login) { setBody(FormDataContent(parameters { append(username, username) append(password, password) })) }.body()4.8 文件上传Multipart// Retrofit Multipart POST(upload) suspend fun upload( Part file: MultipartBody.Part, Part(desc) desc: RequestBody ): UploadResult // Ktor import io.ktor.client.request.forms.* import io.ktor.http.content.* suspend fun upload(fileBytes: ByteArray, fileName: String, desc: String): UploadResult client.post(upload) { setBody(MultiPartFormDataContent( formData { append(desc, desc) append(file, fileBytes, Headers.build { append(HttpHeaders.ContentType, image/jpeg) append(HttpHeaders.ContentDisposition, filename\$fileName\) }) } )) }.body()4.9 完整 URLUrl// Retrofit GET suspend fun getByUrl(Url url: String): Response // Ktor suspend fun getByUrl(url: String): Response client.get(url).body()五、返回值基类
网站建设高端定制企业官网
RELATED

相关资讯

更多精彩内容,欢迎继续阅读

较早相关资讯

最新相关资讯

【外设】之大彩串口显示屏 2026/11/13 0:43:49

【外设】之大彩串口显示屏

大彩串口屏初步使用 1 .官网下载 STM32 屏幕 GUI 设计资料 http://www.gz-dc.com/category/typeid/4112 找到 STM32 Keil 工程,移植相关代码因项目而异进行移植,由于项目简单,本人只对用到的指令接口进行修改。 比如:注意事项&…

阅读更多 →
无法下载Windows系统iso文件 2026/11/12 23:59:09

无法下载Windows系统iso文件

当我遇到这个问题的时候,我打开了一个网站: 登录 然后我打算下载的时候: 突然那个官方的连接就可以下载了:

阅读更多 →
【清华代码熊】DeepSeek V4.1 Flash 后训练详解 2026/11/13 10:09:00

【清华代码熊】DeepSeek V4.1 Flash 后训练详解

📌 上期解析了 DeepSeek V4.1 Flash 模型架构改进,本期解析 DeepSeek V4.1 Flash 预训练/后训练技术: 🌟 预训练:45T 文本 多模态混合语料、直接训练 sparse attention(取消 DeepSeek V4 的 dense 冷启动&…

阅读更多 →
Shuffle-R1: Efficient RL framework for Multimodal Large Language Models via Data-centric Dynamic ... 2026/11/13 13:31:48

Shuffle-R1: Efficient RL framework for Multimodal Large Language Models via Data-centric Dynamic ...

文章主要内容和创新点 主要内容 本文聚焦于多模态大语言模型(MLLM)强化学习(RL)训练中的效率问题,提出了一个名为Shuffle-R1的框架。研究发现,当前RL训练存在两个关键缺陷: 优势值坍缩(Advantage Collapsing):批次中大多数优势值集中在零附近,导致有效梯度信号被淹…

阅读更多 →
PRvL: Quantifying the Capabilities and Risks of Large Language Models for PII Redaction 2026/11/13 16:11:45

PRvL: Quantifying the Capabilities and Risks of Large Language Models for PII Redaction

一、文章主要内容总结 本文聚焦于利用大型语言模型(LLMs)实现个人身份信息(PII)脱敏的研究,旨在解决传统脱敏方法(如基于规则的系统、领域特定命名实体识别(NER)模型)泛化能力差、跨格式/跨语境适应性弱的问题。 研究通过全面评估多种LLM架构(包括密集型LLM(D-LLM…

阅读更多 →
LLaVA-RE: Binary Image-Text Relevancy Evaluation with Multimodal Large Language Model 2026/11/13 0:02:27

LLaVA-RE: Binary Image-Text Relevancy Evaluation with Multimodal Large Language Model

文章主要内容和创新点 主要内容 本文聚焦于二进制图像-文本相关性评估任务(判断图像与文本“相关”或“不相关”),针对该任务中文本格式多样、相关性定义随场景变化等挑战,提出了基于多模态大语言模型(MLLM)的解决方案LLaVA-RE。 模型设计:LLaVA-RE基于LLaVA 1.5架构,…

阅读更多 →

今日资讯

本周资讯

本月资讯

看完文章仍有疑问?

联系尧图顾问,获取一对一建站咨询

立即免费咨询 📞 400-888-8888
📞 ✉