
回复
在开发鸿蒙应用时,网络请求是一个常见的需求。无论是获取数据还是提交数据,都需要与后端服务器进行交互。在ArkTS中,我们可以使用@ohos.net.http
模块来实现HTTP请求。以下是一个封装好的HTTP请求工具类,支持GET和POST请求。
import http from '@ohos.net.http';
http
模块,用于创建和管理HTTP请求。
export function httpRequestGet(url: string, params?: string)
return httpRequest(url, http.RequestMethod.GET, params);
}
httpRequestGet
函数,用于发送GET请求。url
:请求的URL。params
:可选参数,用于传递查询字符串。Promise<string>
,表示请求的结果。
export function httpRequestPost(url: string, params?: string)
return httpRequest(url, http.RequestMethod.POST, params);
}
httpRequestPost
函数,用于发送POST请求。url
:请求的URL。params
:可选参数,用于传递请求体数据。Promise<string>
,表示请求的结果。
function httpRequest(url: string, method: http.RequestMethod, params?: string): Promise<string> {
let httpRequest = http.createHttp();
let responseResult = httpRequest.request(
url, {
method: method,
readTimeout: 10000, // 读取超时时间,可选
header: {
'Content-Type': 'application/json' // 数据提交方式
},
connectTimeout: 10000, // 连接超时时间
extraData: params
}
);
let getjson: string = '';
return responseResult.then((value: http.HttpResponse) =>
console.log('请求状态 -- > ' + value.responseCode);
if (value.responseCode === 200) {
console.log("请求成功");
let result = `${value.result}`;
getjson = result;
} else {
getjson = '';
}
return getjson;
}).catch(() =>
httpRequest.destroy();
return '';
});
}
httpRequest
函数,用于处理HTTP请求。url
:请求的URL。method
:请求方法,可以是http.RequestMethod.GET
或http.RequestMethod.POST
。params
:可选参数,用于传递查询字符串或请求体数据。Promise<string>
,表示请求的结果。http.createHttp()
创建一个HTTP请求对象。httpRequest.request()
发送请求,配置请求方法、超时时间、请求头和请求体。then
回调中,检查响应状态码,如果状态码为200,表示请求成功,返回响应结果;否则返回空字符串。catch
回调中,捕获异常并销毁HTTP请求对象,返回空字符串。
let url = 'https://api.example.com/data';
httpRequestGet(url).then((data) => {
console.log('GET请求结果: ', data);
});
let url = 'https://api.example.com/submit';
let params = JSON.stringify({ key: 'value' });
httpRequestPost(url, params).then((data) => {
console.log('POST请求结果: ', data);
});