首页 > 其他分享 >ArkTs 网络请求注意事项

ArkTs 网络请求注意事项

时间:2024-03-12 22:24:51浏览次数:27  
标签:ArkTs http 请求 stringify item JSON 注意事项 data string

此篇以对操作mysql为例

情景一  post请求传递数据

import http from '@ohos.net.http';
let httpRequest = http.createHttp();
// 用于订阅HTTP响应头,此接口会比request请求先返回。可以根据业务需要订阅此消息
// 从API 8开始,使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。 8+
httpRequest.on('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header));
});
//根据后端字段建类
class CourseDetails {
coursename: string;
teacher: string;
classroom: string;

constructor(coursename: string, teacher: string, classroom: string) {
this.coursename = coursename;
this.teacher = teacher;
this.classroom = classroom;
}
}

@Entry
@Component
struct AxiosPage {
//创建实例
courseDetails: CourseDetails = new CourseDetails('软工', '王老师', '206');
//eg:接收返回的数据
@State Return:string = 'error'

get() {
//转json用于发送
const requestBody = JSON.stringify(this.courseDetails);

httpRequest.request(
"http://localhost:8080/newcourse",
{
method: http.RequestMethod.POST,
header: {
'Content-Type': 'application/json'
},
// 使用JSON.stringify将对象转换为JSON字符串传递给后端
extraData: requestBody,
expectDataType: http.HttpDataType.STRING,
usingCache: true,
priority: 1,
connectTimeout: 60000,
readTimeout: 60000,
usingProtocol: http.HttpProtocol.HTTP1_1,
}, (err, data) => {
if (!err) {
console.info('Result:' + JSON.stringify(data.result));
console.info('code:' + JSON.stringify(data.responseCode));
console.info('header:' + JSON.stringify(data.header));
console.info('cookies:' + JSON.stringify(data.cookies)); // 8+
//告诉编译器这是json字符串,然后赋值渲染
this.Return = data.result as string
} else {
console.info('error:' + JSON.stringify(err));
httpRequest.off('headersReceive');
httpRequest.destroy();
}
}
);
}

build() {
Row() {
Column() {
Text(this.Return)
Button('发送')
.onClick(() => this.get())
}
.width('100%')
}
.height('100%')
}
}

情景二 get获取List

import http from '@ohos.net.http';
let httpRequest = http.createHttp();
// ... (订阅HTTP响应头部分不变)
//根据后端字段建类
class BookDetails {
  id: number;
  bookId: number;
  bookName: string;
  author: string;
  publishingHouse: string;
  num: number;

  constructor(item: any) {
    this.id = item.id;
    this.bookId = item.bookId;
    this.bookName = item.bookName;
    this.author = item.author;
    this.publishingHouse = item.publishingHouse;
    this.num = item.num;
  }
}

@Entry
@Component
struct AxiosPage {
//创建对象数组 @State niao: BookDetails[] = [] async get() { httpRequest.request( "http://localhost:8080/book", { method: http.RequestMethod.GET, header: { 'Content-Type': 'application/json' }, // GET请求不需要传递extraData usingCache: true, priority: 1, connectTimeout: 60000, readTimeout: 60000, usingProtocol: http.HttpProtocol.HTTP1_1, }, (err, data) => { if (!err) { console.info('Result:' + JSON.parse(JSON.stringify(data.result))); const res = JSON.parse(data.result as string) //一般后端会返回json格式,转对象数组赋值this.niao = res } else { console.info('error:' + JSON.stringify(err)); httpRequest.off('headersReceive'); httpRequest.destroy(); } } ); } build() { Column({ space: 12 }) { Row() { List() { ForEach(this.niao, (item) => { ListItem() { Row() { Text(item.bookName) Text(item.author) ...... } } }) } .width('100%') .height('100%') //循环渲染 } .backgroundColor(Color.Red) .width('100%') .height('50%') Button('发送') .onClick(() => this.get()) } .width('100%') } }




配套springboot代码
@GetMapping
public List<Book> getBook(){
return bookService.list();
}
 

 

标签:ArkTs,http,请求,stringify,item,JSON,注意事项,data,string
From: https://www.cnblogs.com/zeyangshuaige/p/18069482

相关文章

  • React — 请求模块(http)封装、API模块封装
    一、请求模块封装//axios封装//根域名配置//超时//请求拦截器/响应拦截器importaxiosfrom'axios'consthttp=axios.create({baseURL:"",timeout:5000})//在发送请求之前拦截插入自定义配置对于参数的处理http.interceptors.request.use(config......
  • 请求模块 LL
     1、CBV源码分析#视图层fromdjango.shortcutsimportrender,HttpResponsefromdjango.viewsimportViewclassCBVTest(View):#通过调度(dispatch)分发请求defdispatch(self,request,*args,**kwargs):passsuper().dispatch(request,......
  • python得scrapy提取数据 xpath注意事项
    在提取器过滤数据这个地方被坑了很久,确实有点坑,有点难以理解,多注意下就可以了。frommultiprocessingimportallow_connection_picklingfromscrapy.spidersimportSpiderfrom..itemsimportCnblogshaha01ItemclasscnblogSpider(Spider):name="cnblogsHAHA01"#定......
  • 不同请求方式参数常用写法
    1.get请求(参数为对象)请求地址是,参数用&拼接:例如:参数格式为一个对象:请求地址:请求写法:exportfunctionapprovalList(data){returnrequest({url:'/approval/list',method:'get',params:data,//关键词params});}2.get请......
  • Http请求头
    Accept:指定客户端能够接收的内容类型,内容类型中的先后次序表示客户端接收的先后次序。实例:Accept:text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5备注:在Prototyp(1.5)的Ajax代码封装中,将Accept默认设置为“text/javascri......
  • Django请求生命周期流程图
    Django请求生命周期流程图流程如下:浏览器发送请求(Http请求)web服务网关接口(Django默认的wsgiref模块不能承受高并发,最大只有1000左右)中间件>>缓存数据库(返回给中间件已经缓存过的数据)urls.py(路由层)views.py(视图层)templates(模板层:存放html静态......
  • 【C#】HttpWebRequest 接口请求,添加基础Basic认证
    C#,调用对方接口,POST方法,Basic账号密码身份认证。stringurl="";stringaccount="";stringpwd="";JObjectpostData=newJObject();HttpWebRequestrequest=(HttpWebRequest)WebRequest.Create(url);request.Method="POST";re......
  • 解决问题:HTTP 错误 500.19 - Internal Server Error 无法访问请求的页面,因为该页的相
      缺少AspNetCoreModuleV2模块,下载安装即可。ps:.netframework是可以直接发布,IIS指定就能正常访问的。但aspnetcore项目略有不同,要额外安装一个模块,如果没有安装,会报HTTP错误500.19-InternalServerError的错。1、官方版本地址:https://dotnet.microsoft.com/down......
  • Java Http Get Post 请求工具类
    importcom.alibaba.fastjson.JSONObject;importorg.apache.http.NameValuePair;importorg.apache.http.client.config.RequestConfig;importorg.apache.http.client.entity.UrlEncodedFormEntity;importorg.apache.http.client.methods.CloseableHttpResponse;importorg......
  • Vue项目中封装axios统一管理http请求
    <divid="content_views"class="markdown_viewsprism-tomorrow-night"><svgxmlns="http://www.w3.org/2000/svg"style="display:none;"><pathstroke-lineca......