
【arkTs】应用开发之http数据请求+调用大模型示例
【代码】【OpenHarmony】arkts应用开发之http数据请求+调用大模型示例。
·
使用示例
requestHttp
import http from '@ohos.net.http';
// import console from '../utils/console';
const TAG="[HttpService]"
export class HttpService{
/**
* HttpRequest对象,承担了发起/取消、订阅响应事件的职责
*/
private httpClient:http.HttpRequest | undefined = undefined;
public response:http.HttpResponse | undefined = undefined;
constructor(){
this.createHttpRequest();
this.onHeaderReceive();
}
/**
* 创建HttpRequest对象,并赋值给httpClient
*/
private createHttpRequest(){
console.info(TAG,"start create HttpRequest");
this.httpClient=http.createHttp();
console.info(TAG,"create HttpRequest sucess ");
}
/**
* 销毁http连接,中断数据请求
*/
public destroy(){
if (this.httpClient != null) {
// 取消订阅HTTP响应头事件
this.httpClient.off('headersReceive');
// 取消订阅HTTP流式响应数据接收事件
this.httpClient.off('dataReceive');
this.httpClient.destroy();
console.info(TAG, "HttpRequest destroyed")
}
}
/**
* 用于订阅http响应头,此接口会比request请求先返回。可以根据业务需要订阅此消息
* 从API 8开始,使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)
*/
private onHeaderReceive(){
if (this.httpClient != null){
this.httpClient.on("headersReceive",(data)=>{
console.info(TAG,"ResponseHeader:"+JSON.stringify(data));
})
}
}
/**
* 根据url和请求参数,向服务端发送http请求
* @param url
* @param param
*/
public requestHttp(url:string,param:RequestParam): Promise<http.HttpResponse>{
console.info(TAG,"start request:"+JSON.stringify(param));
let requestOption : http.HttpRequestOptions = {
method: http.RequestMethod.POST, //请求方式POST GET
extraData: param.extraData, //body参数
header: param.header, //header
readTimeout: param.readTimeout,
connectTimeout: param.connectTimeout
}
console.info(TAG, "the request param is:" + JSON.stringify(requestOption));
console.info(TAG, "the url is:" + url);
if (this.httpClient != null) {
return this.httpClient.request(url,requestOption);
}else {
return http.createHttp().request(url,requestOption);
}
}
public requestHttpWithOption(url:string, requestOption:http.HttpRequestOptions):Promise<http.HttpResponse> {
console.info(TAG, "start request:" + JSON.stringify(requestOption));
if (this.httpClient == null) {
return http.createHttp().request(url, requestOption);
} else {
return this.httpClient.request(url, requestOption);
}
}
}
/**
* 请求参数接口
*/
export interface RequestParam {
method: string;
extraData?: string | Object | ArrayBuffer;
header?: Object; // default is 'content-type': 'application/json'
readTimeout?: number; // default is 60s
connectTimeout?: number; // default is 60s.
}
let httpService:HttpService=new HttpService();
export default httpService
requestInStream
// 引入包名
import http from '@ohos.net.http';
import { BusinessError } from '@ohos.base';
import { RequestParam } from '../HttpService'
import { util } from '@kit.ArkTS';
import { resultFormat } from '../UiConstants';
const TAG="[HttpStreamService]"
export class HttpStreamService {
/**
* HttpRequest对象,承担了发起/取消、订阅响应事件的职责
*/
private httpClient:http.HttpRequest | undefined = undefined;
constructor(){
this.httpClient = http.createHttp();
this.onHeadersReceive();
this.onDataReceiveProgress();
}
// 用于订阅HTTP响应头事件
private onHeadersReceive(){
if (this.httpClient == null) {
return;
}
this.httpClient.on('headersReceive', (header: Object) => {
console.info(TAG, 'header: ' + JSON.stringify(header));
});
}
// 用于订阅HTTP流式响应数据接收事件
public onDataReceive(callback: (result: string) => void){
if (this.httpClient == null) {
return;
}
this.httpClient.on('dataReceive', (data: ArrayBuffer) => {
console.info(TAG, 'res length: ' + data.byteLength);
const decoder = util.TextDecoder.create(`"utf-8"`);
const str = decoder.decodeWithStream(new Uint8Array(data));
console.info(TAG, "str: " + str);
let resultStr = this.parseStreamResult(str);
callback(resultStr);
});
}
private parseStreamResult(str: string) : string {
let resultArr: Array<string> = str.split('\n');
console.info(TAG, "resultArr is " + resultArr);
console.info(TAG, "resultArr is " + resultArr[3]);
if (resultArr[3] == null) {
return "";
}
let result: resultFormat = JSON.parse(resultArr[3].slice(5));
let resultStr = result.output.choices[0].message.content
return resultStr;
}
// 用于订阅HTTP流式响应数据接收进度事件
private onDataReceiveProgress() {
if (this.httpClient == null) {
return;
}
this.httpClient.on('dataReceiveProgress', (data: Data) => {
console.log(TAG, "dataReceiveProgress receiveSize:" + data.receiveSize + ", totalSize:" + data.totalSize);
});
}
// 用于订阅HTTP流式响应数据接收完毕事件
private onDataEnd() {
if (this.httpClient == null) {
return;
}
this.httpClient.on('dataEnd', () => {
console.info(TAG, 'No more data in response, data receive end');
});
}
public destroy() {
if (this.httpClient == null) {
return;
}
// 取消订阅HTTP响应头事件
this.httpClient.off('headersReceive');
// 取消订阅HTTP流式响应数据接收事件
this.httpClient.off('dataReceive');
// 取消订阅HTTP流式响应数据接收进度事件
this.httpClient.off('dataReceiveProgress');
// 取消订阅HTTP流式响应数据接收完毕事件
this.httpClient.off('dataEnd');
// 当该请求使用完毕时,调用destroy方法主动销毁
this.httpClient.destroy();
}
async requestHttp(url:string, requestOption:http.HttpRequestOptions):Promise<number> {
console.info(TAG,"start request:"+JSON.stringify(requestOption));
if (this.httpClient == null) {
return http.createHttp().requestInStream(url,requestOption);
} else {
return this.httpClient.requestInStream(url,requestOption);
}
}
}
// 用于订阅HTTP流式响应数据接收进度事件
class Data {
receiveSize: number = 0;
totalSize: number = 0;
}
let httpStreamService:HttpStreamService=new HttpStreamService();
export default httpStreamService
通义千问
import httpStreamService from './HttpStreamService';
import httpService, { RequestParam } from './HttpService';
import http from '@ohos.net.http';
const TAG: string = "[TongYiThousandQHttp]"
const API_KEY = 'xxx';
const GENERATION_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
export class TongYiThousandQHttp {
public static openSEE:boolean = true
private prompt: string = ''
private result: string = ''
private requestOptions: http.HttpRequestOptions = {}
constructor(prompt: string) {
this.prompt = prompt
}
InitParam() {
this.requestOptions = {
method: http.RequestMethod.POST,
header: {
"Content-Type": 'application/json',
Authorization: `Bearer ${API_KEY}`,
'X-DashScope-SSE': 'enable'
},
extraData: {
model: 'qwen-turbo',
input: {
messages: [{ 'role': 'system', 'content': 'You are a helpful assistant.' },
{ 'role': 'user', 'content': this.prompt }]
},
parameters: {
result_format: "message"
}
}
}
}
getHttpResult(callback: (result: string, time: number) => void) {
let time1: Date = new Date();
this.InitParam()
httpService.requestHttpWithOption(GENERATION_URL, this.requestOptions).then((data: http.HttpResponse) => {
console.info(TAG, "send request sucess,the response is:" + JSON.stringify(data));
let time2: Date = new Date();
let costTime = time2.getTime() - time1.getTime();
if (data.responseCode != 200 || data.responseCode == null) {
this.result = '获取结果失败,请重试'
} else {
this.result = data.result as string
}
callback(this.result, costTime)
}).catch((err:Error) => {
console.info(TAG, 'error:' + JSON.stringify(err));
});
}
getHttpStreamResult(callback: (result: string) => void) {
this.InitParam();
httpStreamService.onDataReceive(callback);
httpStreamService.requestHttp(GENERATION_URL, this.requestOptions).then((data: number) => {
console.info(TAG, "requestInStream OK!" + JSON.stringify(data));
}).catch((err: Error) => {
console.info(TAG, "requestInStream ERROR : err = " + JSON.stringify(err));
});
}
}
相关链接
更多推荐
所有评论(0)