ArkTS 申请HTTP
时间: 2025-01-15 21:09:55 浏览: 64
### 如何在 ArkTS 中发起 HTTP 请求
#### 创建 HttpService 类
为了简化 HTTP 请求操作,在 ArkTS 中通常会创建一个 `HttpService` 单例类来管理所有的 HTTP 请求。这有助于统一处理请求配置和错误捕获。
```typescript
import { createHttp } from '@ohos.net.Http';
class HttpService {
private static instance: HttpService;
private httpRequest: any;
private constructor() {
this.httpRequest = createHttp();
}
public static getInstance(): HttpService {
if (!HttpService.instance) {
HttpService.instance = new HttpService();
}
return HttpService.instance;
}
async get(url: string, options?: object): Promise<any> {
const response = await this.httpRequest.request({
url,
method: 'GET',
...options
});
return response.data;
}
async post(url: string, data: object, options?: object): Promise<any> {
const response = await this.httpRequest.request({
url,
method: 'POST',
data,
...options
});
return response.data;
}
}
```
此代码片段展示了如何定义 `HttpService` 类及其 GET 和 POST 方法[^2]。
#### 发起 GET 请求示例
下面是一个简单的例子,展示如何利用上述服务执行 GET 请求:
```typescript
async function fetchData() {
try {
let result = await HttpService.getInstance().get('https://api.example.com/data', {
headers: {'Content-Type': 'application/json'},
timeout: 5000 // 设置超时时间为5秒
});
console.log(result);
} catch (error) {
console.error(error.message);
}
}
fetchData();
```
这段脚本说明了怎样通过 `HttpService` 的实例发出带有自定义头部信息与超时时长的 GET 请求[^1]。
#### 发起 POST 请求示例
同样地,这里也给出了一段用来发送 JSON 数据给服务器端 API 接口的例子:
```typescript
const postData = {"key": "value"};
async function sendData() {
try {
let result = await HttpService.getInstance().post('https://api.example.com/submit', postData, {
headers: {'Content-Type': 'application/json'}
});
console.log(result);
} catch (error) {
console.error(error.message);
}
}
sendData();
```
以上就是关于如何在 ArkTS 应用程序里实现基本的 HTTP 客户端功能的方法介绍[^3]。
阅读全文
相关推荐















