APIRequestContext
此 API 用于 Web API 测试。你可以使用它来触发 API 端点、配置微服务、准备环境或为端到端测试准备服务。
🌐 This API is used for the Web API testing. You can use it to trigger API endpoints, configure micro-services, prepare environment or the service to your e2e test.
每个 Playwright 浏览器上下文都有一个关联的 APIRequestContext,可以通过 BrowserContext.request() 或 Page.request() 访问(这些返回
🌐 Each Playwright browser context has an associated APIRequestContext, accessible via BrowserContext.request() or Page.request() (these return the
相同实例 — page.request 是 page.context().request 的快捷方式)。你也可以使用 APIRequest.newContext() 创建一个独立的、隔离的实例。
Cookie 管理
BrowserContext.request() 和 APIRequestContext 返回的
🌐 The APIRequestContext returned by BrowserContext.request() and
Page.request() 使用与其 BrowserContext 相同的 cookie 容器:
如果你希望 API 请求不与浏览器共享 Cookie,请通过 APIRequest.newContext() 创建一个隔离的上下文。这样的 APIRequestContext 对象将拥有自己独立的 Cookie 存储。
🌐 If you want API requests that do not share cookies with the browser, create an isolated context via APIRequest.newContext(). Such APIRequestContext object will have its own isolated cookie storage.
方法
🌐 Methods
addCookies
Added in: v1.64将 cookies 添加到此请求上下文中。它们会随着匹配的后续请求一起发送。对于 BrowserContext.request() 和 Page.request(),这相当于在相应的浏览器上下文中调用 BrowserContext.addCookies()。
🌐 Adds cookies into this request context. They will be sent with matching subsequent requests. For BrowserContext.request() and Page.request(), this is equivalent to calling BrowserContext.addCookies() on the corresponding browser context.
用法
request.addCookies(Arrays.asList(cookieObject1, cookieObject2));
参数
cookiesList<Cookies>#-
setNameString -
setValueString -
setUrlString (optional)需要
url或domain和path两者。可选。 -
setDomainString (optional)为了让 cookie 也适用于所有子域,请在域名前加一个点,例如:“.example.com”。
url或者同时domain和path是必填项。可选。 -
setPathString (optional)需要
url或domain和path两者。可选。 -
setExpiresdouble (optional)Unix 时间(以秒为单位)。可选。
-
setHttpOnlyboolean (optional)可选的。
-
setSecureboolean (optional)可选的。
-
setSameSiteenum SameSiteAttribute { STRICT, LAX, NONE }(optional)可选的。
-
setPartitionKeyString (optional)对于分区的第三方 Cookie(也称为 CHIPS),分区键。可选。
-
返回
clearCookies
Added in: v1.64从这个请求上下文中移除 cookies。可以接受可选的过滤器。对于 BrowserContext.request() 和 Page.request() 来说,这相当于在对应的浏览器上下文中调用 BrowserContext.clearCookies()。
🌐 Removes cookies from this request context. Accepts optional filter. For BrowserContext.request() and Page.request(), this is equivalent to calling BrowserContext.clearCookies() on the corresponding browser context.
用法
request.clearCookies();
request.clearCookies(new APIRequestContext.ClearCookiesOptions().setName("session-id"));
request.clearCookies(new APIRequestContext.ClearCookiesOptions().setDomain("my-origin.com"));
request.clearCookies(new APIRequestContext.ClearCookiesOptions().setPath("/api/v1"));
request.clearCookies(new APIRequestContext.ClearCookiesOptions()
.setName("session-id")
.setDomain("my-origin.com"));
参数
optionsApiRequestContext.ClearCookiesOptions(optional)
返回
cookies
Added in: v1.64如果没有指定 URL,这个方法会返回所有的 cookie。如果指定了 URL,只有那些会影响这些 URL 的 cookie 会被返回。对于 BrowserContext.request() 和 Page.request(),这相当于在对应的浏览器上下文中调用 BrowserContext.cookies()。
🌐 If no URLs are specified, this method returns all cookies. If URLs are specified, only cookies that affect those URLs are returned. For BrowserContext.request() and Page.request(), this is equivalent to calling BrowserContext.cookies() on the corresponding browser context.
用法
APIRequestContext.cookies();
APIRequestContext.cookies(urls);
参数
返回
delete
Added in: v1.16发送 HTTP(S) DELETE 请求并返回其响应。该方法会从上下文中填充请求的 cookie,并根据响应更新上下文中的 cookie。该方法会自动跟随重定向。
🌐 Sends HTTP(S) DELETE request and returns its response. The method will populate request cookies from the context and update context cookies from the response. The method will automatically follow redirects.
用法
APIRequestContext.delete(url);
APIRequestContext.delete(url, options);
参数
-
目标网址。
-
optionsRequestOptions (optional) Added in: v1.18#可选请求参数。
返回
dispose
Added in: v1.16APIRequestContext.get() 和类似方法返回的所有响应都会被存储在内存中,以便你以后可以调用 APIResponse.body()。该方法会释放其所有资源,对已释放的 APIRequestContext 调用任何方法都会抛出异常。
🌐 All responses returned by APIRequestContext.get() and similar methods are stored in the memory, so that you can later call APIResponse.body().This method discards all its resources, calling any method on disposed APIRequestContext will throw an exception.
用法
APIRequestContext.dispose();
APIRequestContext.dispose(options);
参数
optionsApiRequestContext.DisposeOptions(optional)
返回
fetch
Added in: v1.16发送 HTTP(S) 请求并返回其响应。该方法会从上下文中填充请求的 cookie,并从响应中更新上下文 cookie。该方法会自动跟随重定向。
🌐 Sends HTTP(S) request and returns its response. The method will populate request cookies from the context and update context cookies from the response. The method will automatically follow redirects.
用法
JSON 对象可以直接传递给请求:
🌐 JSON objects can be passed directly to the request:
Map<String, Object> data = new HashMap();
data.put("title", "Book Title");
data.put("body", "John Doe");
request.fetch("https://example.com/api/createBook", RequestOptions.create().setMethod("post").setData(data));
在请求正文中发送文件的常见方式是将它们作为表单字段上传,使用 multipart/form-data 编码,通过指定 multipart 参数:
🌐 The common way to send file(s) in the body of a request is to upload them as form fields with multipart/form-data encoding, by specifiying the multipart parameter:
// Pass file path to the form data constructor:
Path file = Paths.get("team.csv");
APIResponse response = request.fetch("https://example.com/api/uploadTeamList",
RequestOptions.create().setMethod("post").setMultipart(
FormData.create().set("fileField", file)));
// Or you can pass the file content directly as FilePayload object:
FilePayload filePayload = new FilePayload("f.js", "text/javascript",
"console.log(2022);".getBytes(StandardCharsets.UTF_8));
APIResponse response = request.fetch("https://example.com/api/uploadScript",
RequestOptions.create().setMethod("post").setMultipart(
FormData.create().set("fileField", filePayload)));
参数
-
urlOrRequestString | Request#从中获取所有参数的目标 URL 或请求。
-
optionsRequestOptions (optional) Added in: v1.18#可选请求参数。
返回
get
Added in: v1.16发送 HTTP(S) GET 请求并返回其响应。该方法会从上下文中填充请求的 cookie,并根据响应更新上下文中的 cookie。该方法会自动跟随重定向。
🌐 Sends HTTP(S) GET request and returns its response. The method will populate request cookies from the context and update context cookies from the response. The method will automatically follow redirects.
用法
请求参数可以通过 params 选项进行配置,它们将被序列化为 URL 查询参数:
🌐 Request parameters can be configured with params option, they will be serialized into the URL search parameters:
request.get("https://example.com/api/getText", RequestOptions.create()
.setQueryParam("isbn", "1234")
.setQueryParam("page", 23));
参数
-
目标网址。
-
optionsRequestOptions (optional) Added in: v1.18#可选请求参数。
返回
head
Added in: v1.16发送 HTTP(S) HEAD 请求并返回其响应。该方法会从上下文中填充请求的 cookie,并根据响应更新上下文中的 cookie。该方法会自动跟随重定向。
🌐 Sends HTTP(S) HEAD request and returns its response. The method will populate request cookies from the context and update context cookies from the response. The method will automatically follow redirects.
用法
APIRequestContext.head(url);
APIRequestContext.head(url, options);
参数
-
目标网址。
-
optionsRequestOptions (optional) Added in: v1.18#可选请求参数。
返回
patch
Added in: v1.16发送 HTTP(S) PATCH 请求并返回其响应。该方法会从上下文中填充请求的 cookie,并根据响应更新上下文中的 cookie。该方法会自动跟随重定向。
🌐 Sends HTTP(S) PATCH request and returns its response. The method will populate request cookies from the context and update context cookies from the response. The method will automatically follow redirects.
用法
APIRequestContext.patch(url);
APIRequestContext.patch(url, options);
参数
-
目标网址。
-
optionsRequestOptions (optional) Added in: v1.18#可选请求参数。
返回
post
Added in: v1.16发送 HTTP(S) POST 请求并返回其响应。该方法会从上下文中填充请求的 cookie,并根据响应更新上下文中的 cookie。该方法会自动跟随重定向。
🌐 Sends HTTP(S) POST request and returns its response. The method will populate request cookies from the context and update context cookies from the response. The method will automatically follow redirects.
用法
JSON 对象可以直接传递给请求:
🌐 JSON objects can be passed directly to the request:
Map<String, Object> data = new HashMap();
data.put("title", "Book Title");
data.put("body", "John Doe");
request.post("https://example.com/api/createBook", RequestOptions.create().setData(data));
要将表单数据发送到服务器,请使用 form 选项。其值将使用 application/x-www-form-urlencoded 编码方式编码到请求正文中(下面介绍如何使用 multipart/form-data 表单编码发送文件):
🌐 To send form data to the server use form option. Its value will be encoded into the request body with application/x-www-form-urlencoded encoding (see below how to use multipart/form-data form encoding to send files):
request.post("https://example.com/api/findBook", RequestOptions.create().setForm(
FormData.create().set("title", "Book Title").set("body", "John Doe")
));
在请求体中发送文件的常见方法是将它们作为表单字段上传,并使用 multipart/form-data 编码。使用 FormData 构建请求体,并将其作为 multipart 参数传递给请求:
🌐 The common way to send file(s) in the body of a request is to upload them as form fields with multipart/form-data encoding. Use FormData to construct request body and pass it to the request as multipart parameter:
// Pass file path to the form data constructor:
Path file = Paths.get("team.csv");
APIResponse response = request.post("https://example.com/api/uploadTeamList",
RequestOptions.create().setMultipart(
FormData.create().set("fileField", file)));
// Or you can pass the file content directly as FilePayload object:
FilePayload filePayload1 = new FilePayload("f1.js", "text/javascript",
"console.log(2022);".getBytes(StandardCharsets.UTF_8));
APIResponse response = request.post("https://example.com/api/uploadScript",
RequestOptions.create().setMultipart(
FormData.create().set("fileField", filePayload)));
参数
-
目标网址。
-
optionsRequestOptions (optional) Added in: v1.18#可选请求参数。
返回
put
Added in: v1.16发送 HTTP(S) PUT 请求并返回其响应。该方法会从上下文中填充请求的 cookie,并从响应中更新上下文的 cookie。该方法会自动跟随重定向。
🌐 Sends HTTP(S) PUT request and returns its response. The method will populate request cookies from the context and update context cookies from the response. The method will automatically follow redirects.
用法
APIRequestContext.put(url);
APIRequestContext.put(url, options);
参数
-
目标网址。
-
optionsRequestOptions (optional) Added in: v1.18#可选请求参数。
返回
storageState
Added in: v1.16返回此请求上下文的存储状态,包含当前 cookie 和本地存储快照(如果已传递给构造函数)。
🌐 Returns storage state for this request context, contains current cookies and local storage snapshot if it was passed to the constructor.
用法
APIRequestContext.storageState();
APIRequestContext.storageState(options);
参数
optionsApiRequestContext.StorageStateOptions(optional)
返回
属性
🌐 Properties
tracing()
Added in: v1.60用于跟踪通过此 API 请求上下文发出的请求的记录器。
🌐 Tracing recorder for requests made through this API request context.
用法
APIRequestContext.tracing()
返回