概述
简介
HTTP一般采用浏览器/服务器架构进行通信,同样也是一个应用层协议。它基于运输层TCP协议传输数据,并采用了简单的请求-响应方式进行交互,即客户端根据自身需求将相应的请求发送至服务器,而服务器只能根据接收的客户端请求发送响应数据。另外,HTTP是一种无状态协议,不会在服务器端保留客户端状态,因此,HTTP的模型非常简单,便于开发,部署。
HTTP通信接口说明
接口 | 作用 |
---|---|
createHttp() | 创建一个HTTP请求 |
request | 根据URL网址,发起HTTP网路请求 |
destroy | 中断请求任务 |
on(type: ‘headersReceive’) | 订阅HTTP Response Header事件 |
off(type: ‘headersReceive’) | 取消订阅HTTP Response Header事件 |
常见请求方法
方法 | 作用 |
---|---|
GET | 请求指定的页面信息,并返回实体主体 |
HEAD | 类似于GET请求,只不过返回的响应中没有具体的内容,用于获取报头 |
POST | 向指定资源提交数据并处理请求(例如提交表单或者上传文件)。数据被包含在请求体中,POST请求可能会导致新的资源的建立或已有的资源的修改。 |
PUT | 使用从客户端向服务器传送的数据取代指定的文档内容 |
DELETE | 请求服务器删除指定的页面 |
CONNECT | HTTP/1.1协议中预留给能够将连接改为管道方式的代理服务器 |
OPTIONS | 允许客户端查看服务器的性能 |
TRACE | 回显服务器收到的请求,主要用于测试或诊断 |
PATCH | 是对PUT方法的补充,用来对已知资源进行局部更新 |
状态码
当浏览者访问一个网页时,浏览者的浏览器会向网页所在的服务器发出请求,当浏览器接受并显示网页时,此网页所在的服务器会返回一个包含HTTP状态码的信息头用以响应浏览器的请求。
下面是常见的HTTP状态码
- 200:请求成功
- 301:资源(网页等)被永久转移到其他URL
- 404:请求的资源(网页等)不存在
- 500:内部服务器错误
发送HTTP数据请求
基本流程
- 导入HTTP模块
import {http} from '@kit.NetworkKit'
import { BusinessError} from '@kit.BasicServicesKit'
- 创建httpRequest对象。需要注意的是,每个httpRequest对象对应一个HTTP请求任务,不可复用。
let httpRequest = http.createHttp();
- 通过httpRequest对象发起HTTP请求。
httpRequest.request(
//填写http请求的URL地址,可以带参数也可以不带。url地址需要开发者自定义,请求的参数在extraData中指定
TARGET_URL,
{
header: {
'content-Type': 'application/json'
},
extraData: 'data to send',
expectDataType: http.HttpDataType.STRING, //可选,指定返回数据据的类型
usingCache: true,
}, (err: BusinessError, data: http.HttpResponse) => {
// ...
})
- 取消订阅HTTP响应头事件
调用该对象的off()方法,取消订阅HTTP响应头事件。
httpRequest.off('headersReceive');
- 调用destroy()方法销毁
当该请求使用完毕时,调用destroy()方法销毁。
httpRequest.destroy();
数据请求
import {http} from '@kit.NetworkKit'
import { BusinessError} from '@kit.BasicServicesKit'
import {common} from '@kit.AbilityKit'
import Logger from '../common/Logger';
import { promptAction } from '@kit.ArkUI';
const LOG_TAG: string = '[Sample_HttpRequestDemo]';
const TARGET_URL: string = '';
enum ComponentId {
NORMAL_RESULT_ID = 'normalReqResult',
STREAM_RESULT_ID = 'streamReqResult',
HTTP_BUTTON = 'HttpButton',
STREAM_HTTP_BUTTON = 'StreamHttpButton',
HTTP_TITLE = 'HttpTitleId'
};
@Entry
@Component
struct Index {
@State normalReqRequest: ResourceStr = '';
@State ReqResult: ResourceStr = ''
build() {
Column() {
Text($r('app.string.HTTP_Request_Example'))
.fontSize(20)
.id(ComponentId.HTTP_TITLE)
.margin({bottom: 20})
Button($r('app.string.HTTP_Request_Button'))
.onClick(() => {
this.sendHttpRequest();
})
.width('80%')
.height(50)
.margin({top: 20})
.backgroundColor(Color.Blue)
.fontColor(Color.White)
.fontSize(20)
.id(ComponentId.HTTP_BUTTON)
}
.height('100%')
.width('100%')
}
private sendHttpRequest() {
this.normalReqRequest = $r('app.string.testing')
let httpRequest = http.createHttp();
httpRequest.on('headersReceive', (header) => {
Logger.info(`${LOG_TAG} header: ${JSON.stringify(header)}`);
})
httpRequest.request(
//填写http请求的URL地址,可以带参数也可以不带。url地址需要开发者自定义,请求的参数在extraData中指定
TARGET_URL,
{
method: http.RequestMethod.POST, // 可选,默认为http.RequestMethod.GET,用于从服务器获取数据,而POST方法用于向服务器上传数据。
header: {
'Content-Type': 'application/json' //表示客户端发送给服务器的数据是 JSON格式的字符串
},
extraData: 'data to send',
expectDataType: http.HttpDataType.STRING, //可选,指定返回数据据的类型
usingCache: true,
}, (err: BusinessError, data: http.HttpResponse) => {
if (!err) {
this.normalReqRequest = $r('app.string.httpSendSuccess');
promptAction.showToast({
message: this.normalReqRequest,
duration: 4000,
bottom: 300
})
// data.result为HTTP响应内容
Logger.info(`${LOG_TAG} Result: ${JSON.stringify(data.result)}`);
Logger.info(`${LOG_TAG} code: ${JSON.stringify(data.responseCode)}`);
// data.header为HTTP响应头
Logger.info(`${LOG_TAG} header: ${JSON.stringify(data.header)}`);
Logger.info(`${LOG_TAG} cookies: ${JSON.stringify(data.cookies)}`);
// 当该请求使用完毕时,调用destroy方法主动销毁。
httpRequest.destroy();
} else {
this.normalReqRequest = 'error:' + JSON.stringify(err);
promptAction.showToast({
message: this.normalReqRequest,
duration: 4000, // 持续时间
bottom: 300 // 与底间隔
});
Logger.error(`${LOG_TAG} error: ${JSON.stringify(err)}`);
// 取消订阅HTTP响应头事件
httpRequest.off('headersReceive');
// 当该请求使用完毕时,调用destroy方法主动销毁
httpRequest.destroy();
}
})
}
}
string.json
{
"string": [
{
"name": "module_desc",
"value": "module description"
},
{
"name": "EntryAbility_desc",
"value": "description"
},
{
"name": "EntryAbility_label",
"value": "HTTP_case"
},
{
"name": "HTTP_Request_Button",
"value": "HTTP_Request_Button"
},
{
"name": "HTTP_Request_Example",
"value": "HTTP_Request"
},
{
"name": "Stream_HTTP_Request_Button",
"value": "Stream_HTTP_Request_Button"
},
{
"name": "testSuccess",
"value": "httpFlowSendSuccess"
},
{
"name": "testFail",
"value": "Faliure"
},
{
"name": "testing",
"value": "Testing"
},
{
"name": "httpSendSuccess",
"value": "httpSendSuccess"
},
{
"name": "grant_internet",
"value": "grant_internet"
}
]
}