前置条件
在使用 HTTP 请求功能前,请确保:
导入模块:在脚本开头使用
import http from 'pts/http' 导入 HTTP 模块。脚本结构:所有请求代码需放在
export default function() 函数中执行。URL 格式:确保目标 URL 格式正确,支持
http:// 和 https:// 协议。网络连通性:确保压测环境能够访问目标服务器。
注意事项
错误处理:建议使用
check() 函数验证响应状态码和内容,确保请求成功。超时设置:对于可能响应较慢的接口,建议设置合理的
timeout 值。响应体大小:如果响应体很大且不需要检查内容,可以设置
discardResponseBody: true 以节省内存。Content-Type:发送 POST/PUT/PATCH 请求时,务必根据请求体格式设置正确的
Content-Type。文件上传:使用 FormData 上传文件时,文件必须提前上传到压测场景中,并使用
open() 函数读取。并发控制:批量请求时,注意合理设置
parallel 值,避免对目标服务器造成过大压力。URL 编码:查询参数和表单数据会自动进行 URL 编码,无需手动编码。
重定向:默认会跟随重定向,可以通过
maxRedirects 控制最大重定向次数。HTTP GET 请求
函数说明
http.get() 用于发起 HTTP GET 请求,适用于获取资源、查询数据等场景。该方法在脚本模式的压测场景中使用,支持设置请求头、查询参数等配置。函数签名
http.get(url: string, options?: Request): Response
参数说明
url (string,必填):目标请求的完整 URL 地址,支持
http:// 和 https:// 协议。options (Request,可选):请求配置对象,包含以下可选字段:
headers (Record<string, string>):自定义请求头,如 {'User-Agent': 'pts-engine', 'Connection': 'keep-alive'}。query (Record<string, string>):URL 查询参数,会自动拼接到 URL 后面。timeout (number):请求超时时间,单位为毫秒,包括连接时间、任何重定向和读取响应正文的时间。maxRedirects (number):最大重定向跳转次数。discardResponseBody (boolean):是否丢弃响应体,适用于响应体太大且不需要进行 check 的场景。service (string):服务标识,用于在报表中将不同 URL 的请求归类到同一个服务下。basicAuth (BasicAuth):基础鉴权配置。chunked (function):分块传输回调函数,函数签名为 (body: string) => void,当数据以一系列分块的形式进行发送时,会按行读取响应体并进行回调函数的运行。contentLength (number):记录关联内容的长度。-1表示长度未知,>=0表示可以从 body 中读取给定的字节数。返回值说明
statusCode (number):HTTP 状态码,如200、404、500等。status (string):HTTP 状态消息,如 "200 OK"。body (string):响应体内容,原始字符串格式。headers (Record<string, string>):响应头信息。contentLength (number):服务器响应体长度。proto (string):协议,如 "HTTP/1.0"。request (Request):为获得此响应而发送的请求。responseTimeMS (number):请求的响应时间,单位为毫秒。json() (方法):将响应体反序列化为 JSON 对象,仅当响应体为有效的 JSON 字符串时使用。使用限制
URL 必须包含完整的协议前缀(
http:// 或 https://)。查询参数值必须是字符串类型。
如果响应体不是有效的 JSON 格式,调用
json() 方法会抛出异常。示例
示例1:简单 GET 请求
本示例演示如何发起最简单的 GET 请求,并检查响应状态码和解析 JSON 响应体。
import http from 'pts/http';import { check, sleep } from 'pts';export default function () {// 发起简单的 GET 请求const resp1 = http.get('http://mockhttpbin.pts.svc.cluster.local/get');// 输出原始响应体console.log(resp1.body);// 如果响应体是 JSON 格式,使用 json() 方法转换为对象console.log(resp1.json());// 检查响应状态码是否为 200check('status is 200', () => resp1.statusCode === 200);// 等待 1 秒sleep(1);}
示例2:带请求头和查询参数的 GET 请求
本示例演示如何设置自定义请求头和 URL 查询参数,适用于需要传递特定头部信息或查询条件的场景。
import http from 'pts/http';import { check } from 'pts';export default function () {// GET 请求,包含自定义请求头和查询参数const resp2 = http.get('http://mockhttpbin.pts.svc.cluster.local/get', {headers: {'Connection': 'keep-alive','User-Agent': 'pts-engine','Accept': 'application/json'},query: {'name1': 'value1','name2': 'value2',}});// 从 JSON 响应中提取查询参数值console.log(resp2.json().args.name1); // 输出: 'value1'// 验证响应中的查询参数值check('body.args.name1 equals value1', () => resp2.json().args.name1 === 'value1');}
示例 3:带超时和重定向配置的 GET 请求
本示例演示如何设置请求超时时间和最大重定向次数,适用于需要控制请求行为的场景。
import http from 'pts/http';import { check } from 'pts';export default function () {const resp = http.get('http://mockhttpbin.pts.svc.cluster.local/get', {headers: {'User-Agent': 'pts-engine'},query: {'page': '1','size': '10'},timeout: 5000, // 设置超时时间为 5 秒maxRedirects: 3 // 最大允许 3 次重定向});check('request success', () => resp.statusCode === 200);}
HTTP POST 请求(JSON 格式)
函数说明
http.post() 用于发起 HTTP POST 请求,适用于创建资源、提交数据等场景。当请求体为对象时,默认会序列化为 JSON 格式发送。函数签名
http.post(url: string, body?: string | object | Record<string, string>, options?: Request): Response
参数说明
url (string,必填):目标请求的完整 URL 地址
body (string | object | Record<string, string>,可选):请求体内容。
如果为对象,会自动序列化为 JSON 字符串,并设置
Content-Type: application/json。如果为字符串,直接作为请求体发送。
如果为
Record<string, string>,可以用于表单编码等场景。options (Request,可选):请求配置对象,字段同
http.get() 方法,可设置 headers、query、timeout、maxRedirects、discardResponseBody、service 等。返回值说明
使用限制
当 body 为对象时,系统会自动序列化为 JSON 字符串并设置
Content-Type: application/json 请求头,也可以手动设置。如果响应体不是有效的 JSON 格式,调用
json() 方法会抛出异常。示例
示例1:发送 JSON 格式的 POST 请求
本示例演示如何发送 JSON 格式的 POST 请求,适用于调用 RESTful API 创建或更新资源的场景。
import http from 'pts/http';import { check } from 'pts';export default function () {// 发送 POST 请求,body 为对象会自动序列化为 JSONconst resp = http.post('http://mockhttpbin.pts.svc.cluster.local/post',{user_id: '12345',username: 'testuser',email: 'test@example.com'},{headers: {'Content-Type': 'application/json',},});// 解析响应 JSON 并提取数据console.log(resp.json().json.user_id); // 输出: 12345// 验证响应数据check('body.json.user_id equals 12345', () => resp.json().json.user_id === '12345', resp);}
示例 2:发送字符串格式的 POST 请求
本示例演示如何发送字符串格式的请求体,适用于需要发送原始字符串数据的场景。
import http from 'pts/http';import { check } from 'pts';export default function () {// 发送字符串格式的 POST 请求const resp = http.post('http://mockhttpbin.pts.svc.cluster.local/post','raw string data',{headers: {'Content-Type': 'text/plain',},});check('request success', () => resp.statusCode === 200);console.log(resp.json().data); // 输出: 'raw string data'}
HTTP POST 请求(x-www-form-urlencoded 格式)
函数说明
当需要发送表单数据时,可以使用
application/x-www-form-urlencoded 格式。这种格式适用于传统的 HTML 表单提交场景。参数说明
url (string,必填):目标请求的完整 URL 地址。
body (object,必填):表单数据对象,键值对会被编码为 URL 编码格式。
options (Request,必填):请求配置对象,必须设置
Content-Type: application/x-www-form-urlencoded 请求头。使用限制
必须显式设置
Content-Type: application/x-www-form-urlencoded 请求头,否则服务器可能无法正确解析表单数据。body 对象中的值必须是字符串类型,非字符串值会被转换为字符串。
示例:发送表单编码的 POST 请求
本示例演示如何发送
application/x-www-form-urlencoded 格式的 POST 请求,适用于提交 HTML 表单数据的场景。import http from 'pts/http';import { check } from 'pts';export default function () {// 发送表单编码格式的 POST 请求const resp = http.post('http://mockhttpbin.pts.svc.cluster.local/post',{user_id: '12345',action: 'login',timestamp: '1234567890'},{headers: {'Content-Type': 'application/x-www-form-urlencoded',},});// 验证 Content-Type 请求头console.log(resp.json().headers['Content-Type']); // 输出: application/x-www-form-urlencoded// 从响应中提取表单数据console.log(resp.json().form.user_id); // 输出: 12345// 验证表单数据check('body.form.user_id equals 12345', () => resp.json().form.user_id === '12345', resp);}
HTTP POST 请求(multipart/form-data 格式)
函数说明
http.FormData 用于构造 multipart/form-data 格式的请求体,适用于需要上传文件或同时发送文本和文件的场景。通过 new http.FormData() 创建实例,使用 append() 方法添加字段,最后通过 body() 方法获取请求体。相关函数
new http.FormData():创建 FormData 实例。
formData.append(key, value):向 FormData 中添加字段,value 可以是字符串或
http.file() 返回的 File 对象。formData.body():返回 FormData 的请求体内容(ArrayBuffer 格式),调用后不能再进行 append 操作。
formData.contentType():返回 FormData 的 Content-Type 值,包含 boundary 信息。
http.file(data, name?, contentType?):创建文件对象,用于上传文件。
data (string | ArrayBuffer,必填):文件内容,通常使用 open() 函数的返回值。name (string,可选):文件名,默认为纳秒级时间戳。contentType (string,可选):文件内容类型,默认为 application/octet-stream。使用限制
调用
formData.body() 后不能再调用 append() 方法。必须使用
formData.contentType() 返回的值设置 Content-Type 请求头。文件数据必须通过
open() 函数读取或使用 ArrayBuffer 格式。示例
示例1:上传文本和文件
本示例演示如何同时上传文本字段和文件,适用于文件上传表单的场景。
import http from 'pts/http';import { check } from 'pts';// 读取文件内容(文件需提前上传到压测场景中)const fileData = open("./sample/tmp.js");export default function () {// 创建 FormData 实例const formData = new http.FormData();// 添加文本字段formData.append('data', 'some data');formData.append('description', 'This is a test file');// 添加文件字段,使用 http.file() 创建文件对象formData.append('file', http.file(fileData));// 发送 POST 请求,使用 formData.body() 作为请求体const resp = http.post('http://mockhttpbin.pts.svc.cluster.local/post', formData.body(), {headers: {'Content-Type': formData.contentType() // 必须使用 formData.contentType() 返回的值}});// 验证 Content-Type 包含 multipart/form-dataconsole.log(resp.json().headers['Content-Type']); // 输出: multipart/form-data; boundary=xxxxx// 验证文本字段console.log(resp.json().form.data); // 输出: some data// 验证文件大小console.log(resp.json().files.file.length); // 输出文件字节数,如: 801// 检查表单数据check('body.form.data equals some data', () => resp.json().form.data === 'some data');}
示例2:上传多个文件
本示例演示如何上传多个文件,适用于需要同时上传多个文件的场景。
import http from 'pts/http';import { check } from 'pts';const file1 = open("./sample/file1.txt");const file2 = open("./sample/file2.jpg");export default function () {const formData = new http.FormData();// 添加多个文件,可以指定文件名和内容类型formData.append('document', http.file(file1, 'document.txt', 'text/plain'));formData.append('image', http.file(file2, 'photo.jpg', 'image/jpeg'));formData.append('category', 'uploads');const resp = http.post('http://mockhttpbin.pts.svc.cluster.local/post', formData.body(), {headers: {'Content-Type': formData.contentType()}});check('upload success', () => resp.statusCode === 200);console.log('Document size:', resp.json().files.document.length);console.log('Image size:', resp.json().files.image.length);}
HTTP PUT 请求
函数说明
http.put() 用于发起 HTTP PUT 请求,适用于完整更新资源的场景。PUT 请求通常需要提供完整的资源数据。函数签名
http.put(url: string, body?: string | object | Record<string, string>, options?: Request): Response
参数说明
参数与
http.post() 方法相同。返回值说明
示例:更新资源
本示例演示如何使用 PUT 请求更新资源,适用于 RESTful API 中更新完整资源的场景。
import http from 'pts/http';import { check } from 'pts';export default function () {// 使用 PUT 请求更新资源const resp = http.put('http://mockhttpbin.pts.svc.cluster.local/put',{id: '12345',name: 'Updated Name',status: 'active'},{headers: {'Content-Type': 'application/json',},});check('update success', () => resp.statusCode === 200);console.log(resp.json().json.name); // 输出: Updated Name}
HTTP DELETE 请求
函数说明
http.delete() 用于发起 HTTP DELETE 请求,适用于删除资源的场景。函数签名
http.delete(url: string, options?: Request): Response
参数说明
url (string,必填):目标请求的完整 URL 地址。
options (Request,可选):请求配置对象,字段同
http.get() 方法,可设置 headers、query、timeout、maxRedirects、discardResponseBody、service 等。返回值说明
示例:删除资源
本示例演示如何使用 DELETE 请求删除资源,适用于 RESTful API 中删除资源的场景。
import http from 'pts/http';import { check } from 'pts';export default function () {// 使用 DELETE 请求删除资源const resp = http.delete('http://mockhttpbin.pts.svc.cluster.local/delete', {headers: {'Authorization': 'Bearer token123'},query: {'id': '12345'}});check('delete success', () => resp.statusCode === 200 || resp.statusCode === 204);}
HTTP PATCH 请求
函数说明
http.patch() 用于发起 HTTP PATCH 请求,适用于部分更新资源的场景。PATCH 请求只需要提供需要更新的字段。函数签名
http.patch(url: string, body?: string | object | Record<string, string>, options?: Request): Response
参数说明
参数与
http.post() 方法相同。返回值说明
示例:部分更新资源
本示例演示如何使用 PATCH 请求部分更新资源,适用于只需要更新部分字段的场景。
import http from 'pts/http';import { check } from 'pts';export default function () {// 使用 PATCH 请求部分更新资源const resp = http.patch('http://mockhttpbin.pts.svc.cluster.local/patch',{status: 'inactive' // 只更新 status 字段},{headers: {'Content-Type': 'application/json',},});check('patch success', () => resp.statusCode === 200);}
HTTP HEAD 请求
函数说明
http.head() 用于发起 HTTP HEAD 请求,只获取响应头信息,不返回响应体。适用于检查资源是否存在、获取资源元信息等场景。函数签名
http.head(url: string, options?: Request): Response
参数说明
参数与
http.get() 方法相同。返回值说明
示例:检查资源
本示例演示如何使用 HEAD 请求检查资源是否存在,适用于不需要响应体内容的场景。
import http from 'pts/http';import { check } from 'pts';export default function () {// 使用 HEAD 请求检查资源const resp = http.head('http://mockhttpbin.pts.svc.cluster.local/get', {headers: {'User-Agent': 'pts-engine'}});// 检查状态码check('resource exists', () => resp.statusCode === 200);// 获取响应头信息console.log('Content-Type:', resp.headers['Content-Type']);console.log('Content-Length:', resp.headers['Content-Length']);}
HTTP 基础鉴权(Basic Authentication)
函数说明
HTTP 基础鉴权可以通过两种方式实现:
1. 在 URL 中包含用户名和密码:
http://username:password@host/path。2. 使用
basicAuth 配置项(需配合 http.do() 方法使用)。使用限制
URL 中的用户名和密码会以 Base64 编码形式发送。
仅适用于支持 HTTP Basic Authentication 的服务器。
生产环境建议使用更安全的认证方式。
示例:使用 URL 进行基础鉴权
本示例演示如何在 URL 中包含用户名和密码进行基础鉴权,适用于需要简单认证的场景。
import http from 'pts/http';import { check } from 'pts';export default function () {// 在 URL 中包含用户名和密码const user = 'user';const passwd = 'passwd';const resp = http.get(`http://${user}:${passwd}@mockhttpbin.pts.svc.cluster.local/basic-auth/user/passwd`);// 验证认证结果console.log(resp.json().authenticated); // 输出: truecheck('body.authenticated equals true', () => resp.json().authenticated === true);}
HTTP Cookie 使用
函数说明
可以通过在请求头中设置
Cookie 字段来发送 Cookie,适用于需要维护会话状态的场景。使用限制
Cookie 值必须是字符串格式
多个 Cookie 可以使用分号分隔,如:
cookie1=value1; cookie2=value2如果需要自动管理 Cookie,建议使用
http.do() 方法配合相关配置示例:发送 Cookie
本示例演示如何在请求中发送 Cookie,适用于需要传递会话信息的场景。
import http from 'pts/http';import { check } from 'pts';export default function () {// 在请求头中设置 Cookieconst resp = http.get('http://mockhttpbin.pts.svc.cluster.local/cookies', {headers: {cookie: 'k=v; session_id=abc123; user_id=456'}});// 验证 Cookie 是否正确传递console.log(resp.json().cookies.k); // 输出: vconsole.log(resp.json().cookies.session_id); // 输出: abc123check('body.cookies.k equals v', () => resp.json().cookies.k === 'v');}
通用请求方法 http.do()
函数说明
http.do() 是一个通用的 HTTP 请求方法,可以发送任意 HTTP 方法的请求。适用于需要更灵活控制请求参数或使用高级功能的场景。函数签名
http.do(request: Request): Response
参数说明
method (string,必填):HTTP 方法,如 'GET'、'POST'、'PUT'、'DELETE'、'PATCH'、'HEAD' 等。url (string,必填):目标请求的完整 URL 地址。body (string | object | ArrayBuffer,可选):请求体内容,在使用 http.do 方法时才需要指定。headers (Record<string, string>,可选):请求头。query (Record<string, string>,可选):URL 查询参数。timeout (number,可选):请求超时时间(毫秒),包括连接时间、任何重定向和读取响应正文的时间。maxRedirects (number,可选):最大重定向跳转次数。discardResponseBody (boolean,可选):是否丢弃响应体,适用于响应体太大且不需要进行 check 的场景。service (string,可选):服务标识,用于在报表中将不同 URL 的请求归类到同一个服务下。basicAuth (BasicAuth,可选):基础鉴权配置。chunked (function,可选):分块传输回调函数,当数据以一系列分块的形式进行发送时,如果指定了 chunked 函数,会按行读取响应体并进行回调函数的运行。函数签名为 (body: string) => void。contentLength (number,可选):记录关联内容的长度。-1表示长度未知,>=0表示可以从 body 中读取给定的字节数。host (string,可选):host 或 host:port,通常不需要单独指定,使用 url 即可。path (string,可选):路径,相对路径省略前导斜杠,通常不需要单独指定,使用 url 即可。scheme (string,可选):协议,填写 "http" 或 "https",通常不需要单独指定,使用 url 即可。返回值说明
使用限制
method 和 url 字段为必填项。当使用
body 字段时,需要根据内容类型设置相应的 Content-Type 请求头。host、path、scheme 字段通常不需要单独指定,直接使用完整的 url 即可。chunked 回调函数仅在响应体以分块形式传输时才会被调用。示例:使用 http.do() 发送请求
本示例演示如何使用
http.do() 方法发送请求,适用于需要完整控制请求参数的场景。import http from 'pts/http';import { check } from 'pts';export default function () {// 使用 http.do() 发送 POST 请求const req = {method: 'post',url: 'http://mockhttpbin.pts.svc.cluster.local/post',headers: {'Content-Type': 'application/json'},query: {a: '1'},body: {user_id: '12345'},timeout: 5000,maxRedirects: 3};const resp = http.do(req);// 验证查询参数console.log(resp.json().args.a); // 输出: 1// 验证请求体console.log(resp.json().json.user_id); // 输出: 12345check('request success', () => resp.statusCode === 200);}
批量请求 http.batch()
函数说明
http.batch() 用于批量发起多个 HTTP 请求,支持并行执行,适用于需要同时发起多个请求的场景,可以提高压测效率。函数签名
http.batch(requests: Request[], options?: BatchOption): BatchResponse[]
参数说明
requests (Request[],必填):请求配置对象数组,每个元素的结构与
http.do() 方法的参数相同,必须包含 method 和 url 字段。options (BatchOption,可选):批量请求配置选项。
parallel (number,可选):并行执行数,默认值为 20。返回值说明
返回
BatchResponse[] 数组,每个元素包含以下字段:error (string):错误信息,不为空则表示请求出错。response (Response):请求结果,包含 statusCode、body、headers 等属性。使用限制
批量请求的数量建议控制在合理范围内,避免过多请求导致性能问题。
并行数
parallel 的值会影响请求的并发度,需要根据实际情况调整。示例:批量发送请求
本示例演示如何使用
http.batch() 批量发送多个请求,适用于需要同时测试多个接口的场景。import http from 'pts/http';import { check } from 'pts';export default function () {// 批量发送多个请求const responses = http.batch([{method: 'GET',url: 'http://mockhttpbin.pts.svc.cluster.local/get?a=1',headers: { 'User-Agent': 'pts-engine' },query: { b: '2' },},{method: 'POST',url: 'http://mockhttpbin.pts.svc.cluster.local/post',headers: { 'Content-Type': 'application/json' },body: { user_id: '12345' },},{method: 'GET',url: 'http://mockhttpbin.pts.svc.cluster.local/get?c=3',headers: { 'Authorization': 'Bearer token123' },},],// 批量请求配置选项{parallel: 3, // 并行执行 3 个请求});// 处理每个响应responses.forEach((resp, index) => {if (resp.error) {console.log(`Request ${index + 1} error:`, resp.error);} else {console.log(`Request ${index + 1} status:`, resp.response.statusCode);check(`Request ${index + 1} success`, () => resp.response.statusCode === 200);}});// 输出所有响应console.log(JSON.stringify(responses));}
Response 对象常用方法
json() 方法
Response.json() 方法用于将响应体反序列化为 JSON 对象。函数签名
json(): any
返回值
返回代表
Response.body 的 JavaScript 对象。使用限制
仅当响应体为有效的 JSON 字符串时才能使用。
如果响应体不是 JSON 格式,调用此方法会抛出异常。
建议在使用前先检查响应体的
Content-Type 是否为 application/json。示例:解析 JSON 响应
import http from 'pts/http';import { check } from 'pts';export default function () {const resp = http.get('http://mockhttpbin.pts.svc.cluster.local/get', {query: { key: 'value' }});// 检查响应是否为 JSON 格式const contentType = resp.headers['Content-Type'] || '';if (contentType.includes('application/json')) {const data = resp.json();console.log('Parsed JSON:', data);check('has args', () => data.args !== undefined);} else {console.log('Response body:', resp.body);}}