当前位置: 首页 > 科技观察

OpenharmonyeTS的HttpPost请求

时间:2023-03-16 19:58:23 科技观察

更多开源请访问:51CTO开源基础软件社区https://ost.51cto.comAndroid-async-http、AutobahnAndroid、OkGo等库的功能和特性,致力于在OpenHarmony打造一个高效、易用、全面的网络请求库。当前版本的httpclient依赖于系统提供的网络请求能力和上传下载能力!1、安装HttpClient1,打开第三方组件库https://repo.harmonyos.com/#/cn/application/atomService?q=http%20keyword%3AOpenHarmony2,找到我们需要的httpclient3,安装代码:npminstall@ohos/httpclient--save2.添加权限添加权限参考这篇文章:https://ost.51cto.com/posts/13219。三、编写代码1.eTS代码importhttpclientfrom'@ohos/httpclient';从“@ohos/httpclient”导入TimeUnit让httpClientImpl=newhttpclient.HttpClient.Builder().setConnectTimeout(15,TimeUnit.TimeUnit.SECONDS)。setReadTimeout(15,TimeUnit.TimeUnit.SECONDS).build();@Entry@ComponentstructIndex{@Statemessage:string='posttest';@Statesrtbutton:字符串='';build(){Row(){Column(){Text(this.message).fontSize(50).fontWeight(FontWeight.Bold)Text(this.srtbutton).fontSize(50).fontWeight(FontWeight.Bold)Button(){//按钮控件Text('click').fontSize(50).fontWeight(FontWeight.Bold)}.type(ButtonType.Capsule).margin({top:200}).width('50%').height('10%').backgroundColor('#0D9FFB').onClick(()=>{//点击事件letbody={//withparameter"data":"hi!",};letrequestBody=httpclient.RequestBody.create(JSON.stringify(body));让request=newhttpclient.Request.Builder().url("http://192.168.0.141:5000/").method('POST').body(requestBody).addHeader("Content-Type","application/json").params("token","yukoyu").build();httpClientImpl.newCall(request).enqueue((result)=>{console.log("success:"+JSON.stringify(result))this.srtbutton=JSON.stringify(result.data)},(error)=>{console.log("error:"+JSON.stringify(error))})})}.width('100%')}.height('100%')}}2、服务器接口代码importjsonfromflaskimportFlask,requestfromflask_sqlalchemyimportSQLAlchemyfromflask_migrateimportMigratefromflask_restfulimportApifromflask_restfulimportResourceimportdatetimeimportconfigapp=Flask(__name__)app.config.from_object(config)db=SQLAl复制代码chemy(app)api=Api(app)'''测试接口'''classhello(Resource):defpost(self):data=json.loads(request.get_data())print(data)return{"data":"hellopost"}defget(self):return{"data":"helloget"}api.add_resource(hello,'/')migrate=Migrate(app,db)4.测试一,安装效果二,点击效果3,服务端打印post参数测试成功!了解更多开源请访问:51CTO开源基础软件社区https://ost.51cto.com