鸿蒙开发之RCP网络请求
·
一、RCP网络请求
RCP指的是远程通信平台(remote communication platform),RCP提供了网络数据请求功能,相较于Network Kit中HTTP请求能力,RCP更具易用性,且拥有更多的功能。在开发过程中,如果有些场景使用Network Kit中HTTP请求能力达不到预期或无法实现,那么就可以尝试使用RCP中的数据请求功能来实现。
二、RCP的基础使用
import { rcp } from '@kit.RemoteCommunicationKit'
interface Data {
code: number,
msg: string,
data: string
}
@Entry
@Component
struct RCPPage {
@State data: string = 'rpc'
url: string = 'https://v2.xxapi.cn/api/yiyan?type=poetry'
rcpGet() {
// 定义请求头
let headers: rcp.RequestHeaders = {
'accept': 'application/json'
}
const securityConfig: rcp.SecurityConfiguration = {
tlsOptions: {
tlsVersion: 'TlsV1.3'
}
}
// 创建通信会话对象
const session = rcp.createSession({ requestConfiguration: { security: securityConfig } })
// 定义请求对象rep
let req = new rcp.Request(this.url, 'GET', headers)
// 发起请求
session.fetch(req).then((response) => {
let result = response.toJSON() as Data
// 打印日志
console.log('rcp' + JSON.stringify(response))
this.data = result.data
})
}
build() {
Column() {
Text(this.data)
.fontSize(20)
.fontWeight(FontWeight.Bold)
.onClick(() => {
this.rcpGet()
})
}
.width('100%')
.height('100%')
}
}
三、设置会话中URL的基地址
会话中URL的基地址是在发起请求时用作请求地址的前缀。 当我们向服务器发起请求时,该请求的最终的请求地址由会话中URL的基地址与请求路径来构建的。 这使得我们可以将服务器的主机地址与公共路径隔离开来,方便管理和维护。
import { rcp } from '@kit.RemoteCommunicationKit'
interface Data {
code: number,
msg: string,
data: string
}
@Entry
@Component
struct RCPPage {
@State data: string = 'rpc'
rcpSessionGet() {
const sessionConfig: rcp.SessionConfiguration = {
baseAddress: 'https://v2.xxapi.cn',
headers: {
'content-type': 'application/json'
},
requestConfiguration:{
security:{
tlsOptions: {
tlsVersion: 'TlsV1.3'
}
}
}
}
// 创建通信会话对象
const session = rcp.createSession(sessionConfig)
// 定义请求对象rep
let req = new rcp.Request('/api/yiyan?type=poetry', 'GET')
// 发起请求
session.fetch(req).then((response) => {
let result = response.toJSON() as Data
// 打印日志
console.log('rcp' + JSON.stringify(response))
this.data = result.data
})
}
build() {
Column() {
Text(this.data)
.fontSize(20)
.fontWeight(FontWeight.Bold)
.onClick(() => {
this.rcpSessionGet()
})
}
.width('100%')
.height('100%')
}
}
注意:在使用网络请求的时候,需要在module.json5文件中,申请网络权限。
更多推荐


所有评论(0)