Openharmony eTS 之 Http Post請求
作者:yukoyu
Httpclient以人們耳熟能詳?shù)腛KHTTP為基礎,整合Android-async-http,AutobahnAndroid,OkGo等庫的功能特性,致力于在OpenHarmony 打造一款高效易用,功能全面的網(wǎng)絡請求庫。
??想了解更多關(guān)于開源的內(nèi)容,請訪問:??
前言
Httpclient以人們耳熟能詳?shù)腛KHTTP為基礎,整合Android-async-http,AutobahnAndroid,OkGo等庫的功能特性,致力于在OpenHarmony 打造一款高效易用,功能全面的網(wǎng)絡請求庫。當前版本的httpclient依托系統(tǒng)提供的網(wǎng)絡請求能力和上傳下載能力!
一、安裝HttpClient
1、打開第三方組件庫
https://repo.harmonyos.com/#/cn/application/atomService?q=http%20keyword%3AOpenHarmony
2、找到我們需要的httpclient
3、安裝
代碼:
npm install /httpclient --save
二、添加權(quán)限
添加權(quán)限參考這文章: https://ost.51cto.com/posts/13219。
三、編寫代碼
1、eTS代碼
import httpclient from '@ohos/httpclient';
import TimeUnit from '@ohos/httpclient'
let httpClientImpl = new httpclient.HttpClient.Builder().setConnectTimeout(15, TimeUnit.TimeUnit.SECONDS).setReadTimeout(15, TimeUnit.TimeUnit.SECONDS).build();
struct Index {
message: string = 'post 測試';
srtbutton: string = '';
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
Text(this.srtbutton)
.fontSize(50)
.fontWeight(FontWeight.Bold)
Button() { //按鈕控件
Text('點擊')
.fontSize(50)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({
top: 200
})
.width('50%')
.height('10%')
.backgroundColor('#0D9FFB')
.onClick(() => { //點擊事件
let body = { //帶參數(shù)
"data": "hi!",
};
let requestBody = httpclient.RequestBody.create(JSON.stringify(body));
let request = new httpclient.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、服務器接口代碼
import json
from flask import Flask, request
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_restful import Api
from flask_restful import Resource
import datetime
import config
app = Flask(__name__)
app.config.from_object(config)
db = SQLAlchemy(app)
api = Api(app)
'''
測試接口
'''
class hello(Resource):
def post(self):
data = json.loads(request.get_data())
print(data)
return { "data" : "hello post"}
def get(self):
return { "data" : "hello get"}
api.add_resource(hello, '/')
migrate = Migrate(app, db)
四、測試
1、安裝效果
2、點擊效果
3、服務器打印post參數(shù)
測試成功!
責任編輯:jianghua
來源:
鴻蒙社區(qū)