# 探索 HTTP 请求语法

> For the complete documentation index, see [llms.txt](https://www.jetbrains.com.cn/help/idea/llms.txt).

本节介绍 HTTP 请求格式。 有关发送 HTTP 请求和查看 HTTP 响应的详细信息，请参阅 [HTTP 客户端](http-client-in-product-code-editor.html)。

要在 IntelliJ IDEA 代码编辑器中编写 HTTP 请求，请使用以下通用语法：

```HTTP_REQUEST_FULL
Method Request-URI HTTP-Version
Header-field: Header-value

Request-Body

```

Procedure: 在 HTTP 请求中使用注释

* 在请求中，使用  `//`  或  `#`  开始任何一行将其变成注释行。

```HTTP_REQUEST_FULL
// A basic request
GET http://example.com/a/

```

Procedure: 为 HTTP 请求设置名称

要在 [运行/调试配置](http-client-in-product-code-editor.html#http-request-run-debug-configurations)、 [随处搜索](searching-everywhere.html) 和 [运行任何内容](running-anything.html#send_http_requests) 中快速找到请求，可以为其指定一个名称。

* 在请求上方的  `###` 、  `# @name`  或  `# @name =`  旁边输入名称。

![输入 HTTP 请求名称](https://resources.jetbrains.com.cn/help/img/idea/2026.3/aqua_http_request_name.png)

如果请求没有名称，IntelliJ IDEA 将使用其在请求文件中的位置（例如  `#1` ）作为请求名称。 如果请求文件中包含多个同名请求，IntelliJ IDEA 会将请求位置编号附加到每个名称后面。 这将使每个请求名称唯一，以便您可以在   服务  工具窗口、运行/调试配置等中轻松找到所需的请求。

![服务工具窗口中的 HTTP 请求](https://resources.jetbrains.com.cn/help/img/idea/2026.3/aqua_http_request_same_names.png)

Procedure: 使用简短格式进行 GET 请求

* 对于  GET 请求，您可以省略请求方法并且只指定 URI。

```HTTP_REQUEST_FULL
// A basic request
https://example.com/a/

```

在 Java 环境中，您可以使用 [代码补全](auto-completing-code.html) `Ctrl+Space` (Windows), `⌃ Space` (macOS), `⌃ Space` (IntelliJ IDEA Classic (macOS)), `⌃ Space` (macOS System Shortcuts), `Ctrl+Space` (XWin), `Ctrl+Space` (GNOME), `Ctrl+Space` (KDE), `Alt+/` (Emacs), `Ctrl+Space` (Sublime Text), `⌃ Space` (Sublime Text (macOS)), `Ctrl+Space` (Visual Studio), `⌃ Space` (Visual Studio (macOS)), `Ctrl+Space` (NetBeans), `Ctrl+Space` (Eclipse), `⌃ Space` (Eclipse (macOS))来根据已定义的  `@Path` 注解指定 URI。 对 Java 代码中  `@Path`  注释的任何更改都会反映在建议列表的内容中。

Procedure: 在单个文件中编写多个请求

1. 通过在下方键入  `###` 分隔符来标记请求的结束。

```HTTP_REQUEST_FULL
// A basic request
https://example.com/a/

###

```

2. 在分隔符下再写一个请求。

```HTTP_REQUEST_FULL
// A basic request
https://example.com/a/

###

// A second request using the GET method
https://example.com:8080/api/html/get?id=123&value=content

```

Procedure: 设置执行延迟

* `sleep(ms)`  函数／方法可将 HTTP 请求或脚本的执行暂停指定时长（以毫秒为单位）。 这对于各种连接测试、websocket 测试等特别有用。

将  `sleep()`  函数／方法与  `await`  关键字结合使用以暂停执行：  `await sleep(milliseconds)` 。

* 如果想安排一段代码在延迟后运行，而不阻止脚本的其余部分，请使用 [Web API 方法](https://developer.mozilla.org/en-US/docs/Web/API/Window)：

* [setTimeout()](https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout)：安排一个函数／方法在指定毫秒数后运行一次。 返回计时器 ID。

* [clearTimeout()](https://developer.mozilla.org/en-US/docs/Web/API/Window/clearTimeout)：取消使用 `setTimeout()` 设置的超时。 接受计时器 ID。

* 在预请求脚本中，可以延迟 HTTP 请求的实际发送。 在响应处理程序中，使用这些函数／方法来延迟收到响应后的测试执行或逻辑。

```HTTP_REQUEST_FULL
< {%
    const job = setTimeout(() => {
        console.log("This timer is cleared and will not execute.");
    }, 1000);

    console.log("Pre-request: Starting sleep...");
    clearTimeout(job);

    const start = Date.now();
    await sleep(10000);

    console.log(`Pre-request: Finished sleep after ${Date.now() - start}ms`);
    console.log("Pre-request: Proceeding to request.");
%}

GET https://examples.http-client.intellij.net/anything

> {%
    setTimeout(() => {
        console.log("Post-script: One second timer fired during sleep.");
    }, 1000);

    console.log("Post-script: Starting sleep...");

    const start = Date.now();
    await sleep(10000);

    console.log(`Post-script: Finished sleep after ${Date.now() - start}ms`);
    console.log("Post-script: Script execution complete.");
%}
                
```

Procedure: 将长请求分成几行

* 将所有查询字符串行缩进，但第一行除外。

```HTTP_REQUEST_FULL
// Using line breaks with indent
GET http://example.com:8080
    /api
    /html
    /get
    ?id=123
    &value=content

```

> **Tip:**
> URL 部分的缩进大小配置在  `设置 | 编辑器 | 代码样式 | HTTP 请求 | 制表符和缩进 | URL 部分缩进`  中。

* 如果因查询字符串导致 URL 过长，您可以使用专用的上下文操作将每个查询参数放在新行上。 将文本光标放到查询字符串部分，按 `Alt+Enter` (Windows), `⌥ ⏎` (macOS), `⌥ ⏎` (IntelliJ IDEA Classic (macOS)), `⌥ ⏎` (macOS System Shortcuts), `Alt+Enter` (XWin), `Alt+Enter` (GNOME), `Alt+Enter` (KDE), `Alt+Enter` (Emacs), `Alt+Enter` (Sublime Text), `⌥ ⏎` (Sublime Text (macOS)), `Alt+Enter` (Visual Studio), `⌥ ⏎` (Visual Studio (macOS)), `Alt+Enter` (NetBeans), `Ctrl+1` (Eclipse), `⌘ 1` (Eclipse (macOS))（   显示上下文操作​​  ），然后选择   将查询形参放在单独的行中  。

Before:

```HTTP_REQUEST_FULL
GET https://example.com:8080/api/get/html?firstname=John&lastname=Doe&planet=Tatooine&town=Freetown

```

After:

```HTTP_REQUEST_FULL
GET https://example.com:8080/api/get/html?
    firstname=John&
    lastname=Doe&
    planet=Tatooine&
    town=Freetown

```

> **Note:**
> 您可以使用  `设置 | 编辑器 | 代码样式 | HTTP 请求 | 换行与括号 | 查询形参换行 wrap.`  中的 HTTP 客户端代码样式来强制一致地包装查询参数。

* 同样，您可以在请求中格式化正文  `Content-Type: application/x-www-form-urlencoded` 。 请将文本光标放置在正文处，按 `Alt+Enter` (Windows), `⌥ ⏎` (macOS), `⌥ ⏎` (IntelliJ IDEA Classic (macOS)), `⌥ ⏎` (macOS System Shortcuts), `Alt+Enter` (XWin), `Alt+Enter` (GNOME), `Alt+Enter` (KDE), `Alt+Enter` (Emacs), `Alt+Enter` (Sublime Text), `⌥ ⏎` (Sublime Text (macOS)), `Alt+Enter` (Visual Studio), `⌥ ⏎` (Visual Studio (macOS)), `Alt+Enter` (NetBeans), `Ctrl+1` (Eclipse), `⌘ 1` (Eclipse (macOS)) (   显示上下文操作​​  )，然后选择   将 form-urlencoded 形参放在单独的行中  。

Before:

```HTTP_REQUEST_FULL
POST https://ijhttp-examples.jetbrains.com/post
Content-Type: application/x-www-form-urlencoded

key1=value1&key2=value2&key3=value3&key4=value4&key5=value5

```

After:

```HTTP_REQUEST_FULL
POST https://ijhttp-examples.jetbrains.com/post
Content-Type: application/x-www-form-urlencoded

key1 = value1 &
key2 = value2 &
key3 = value3 &
key4 = value4 &
key5 = value5

```

要配置  `x-www-form-urlencoded`  正文的换行，请使用  `设置 | 编辑器 | 代码样式 | HTTP 请求 | 换行与括号 | 表单编码形参换行 wrap.` 。 要配置  `=`  之间以及  `&`  之前的空格，请使用  `设置 | 编辑器 | 代码样式 | HTTP 请求 | Space` 。

Procedure: 访问具有身份验证的 Web 服务

* 根据您正在访问的网络服务，提供 [基础](https://en.wikipedia.org/wiki/Basic_access_authentication)或 [摘要](https://en.wikipedia.org/wiki/Digest_access_authentication)  授权 头。

```HTTP_REQUEST_FULL
// Basic authentication
GET http://example.com
Authorization: Basic username password

###

// Digest authentication
GET http://example.com
Authorization: Digest username password

```

> **Note:**
> 同其他 HTTP 请求元素类似，提供的  `用户名`  和  `密码`  可以通过 [环境变量](http-client-variables.html) 进行参数化。

Procedure: 提供请求消息体

在请求中，在请求体的前面添加一个空行，并执行以下操作之一：

* 请在此处输入请求正文：

```HTTP_REQUEST_FULL
// The request body is provided in place
POST https://example.com:8080/api/html/post HTTP/1.1
Content-Type: application/json
Cookie: key=first-value

{ "key" : "value", "list": [1, 2, 3] }

```

如果您将  Content-Type  标头字段的值设置为 [支持的语言](discover-intellij-idea.html#IntelliJ-IDEA-supported-languages)之一，那么相应的语言片段将会被 [自动注入](using-language-injections.html) 到 HTTP 请求消息体中。 如果未指定  内容类型 ，您可以手动插入语言片段。

* 在 Java 上下文中，您可以使用 [代码补全](auto-completing-code.html) `Ctrl+Space` (Windows), `⌃ Space` (macOS), `⌃ Space` (IntelliJ IDEA Classic (macOS)), `⌃ Space` (macOS System Shortcuts), `Ctrl+Space` (XWin), `Ctrl+Space` (GNOME), `Ctrl+Space` (KDE), `Alt+/` (Emacs), `Ctrl+Space` (Sublime Text), `⌃ Space` (Sublime Text (macOS)), `Ctrl+Space` (Visual Studio), `⌃ Space` (Visual Studio (macOS)), `Ctrl+Space` (NetBeans), `Ctrl+Space` (Eclipse), `⌃ Space` (Eclipse (macOS)) 来根据定义的  `@Produces`  注解指定  `Accept`  标头字段的值。 任何对 Java 代码中  `@Produces` 注释的更改都会反映在建议列表的内容中。

* 要从文件中读取请求正文，请键入  `<` 符号，后跟文件路径。

```GENERIC
// The request body is read from a file
POST https://example.com:8080/api/html/post
Content-Type: application/json

< ./input.json

```

Procedure: 使用 multipart/form-data 内容类型

* 将请求的  内容类型 设置为  multipart/form-data 。 要作为  multipart/form-data  消息的一部分发送文件，请在  Content-Disposition  标头中包含  `文件名`  参数。

```HTTP_REQUEST_FULL
POST https://example.com/api/upload HTTP/1.1
Content-Type: multipart/form-data; boundary=boundary

--boundary
Content-Disposition: form-data; name="first"; filename="input.txt"

// The 'input.txt' file will be uploaded
< ./input.txt

--boundary
Content-Disposition: form-data; name="second"; filename="input-second.txt"

// A temporary 'input-second.txt' file with the 'Text' content will be created and uploaded
Text
--boundary
Content-Disposition: form-data; name="third";

// The 'input.txt' file contents will be sent as plain text.
< ./input.txt --boundary--

```

> **Tip:**
> 为了加快创建  multipart/form-data 请求的速度，请使用   mptr   [实时模板](using-live-templates.html)。

Procedure: 禁用后续重定向

当 HTTP 请求被重定向（收到 3xx 状态码）时，将返回重定向页面的响应。 在   服务  工具窗口中，您可以查看重定向的页面响应以及请求过程中发生的所有重定向。

您可能希望禁用跟随重定向。 在这种情况下，将返回实际的重定向响应头（如 301 或 302）。

* 在请求之前，添加带有  `@no-redirect`  标记的注释行。

```HTTP_REQUEST_FULL
// @no-redirect
example.com/status/301

```

如果您已经有一个重定向的请求，您可以点击   禁用  旁边的  `重定向` 列表，位于   服务  工具窗口中。 这将向初始请求中添加  `@no-redirect`  标记。

![HTTP 响应带有重定向](https://resources.jetbrains.com.cn/help/img/idea/2026.3/aqua_http_response_redirect.png)

Procedure: 禁用将请求保存到请求历史

如有必要，您可以防止请求被保存到 [请求历史记录](http-client-in-product-code-editor.html#requests_history)。 如果请求包含某些敏感数据，而您不希望将其记录到日志中，此方法会很有用。

* 在请求之前，添加带有  `@no-log`  标记的注释行。

```HTTP_REQUEST_FULL
// @no-log
GET example.com/api

```

Procedure: 禁用将接收到的 cookie 保存到 cookies jar

如有必要，您可以防止接收的 cookie [保存到 cookies jar](http-client-in-product-code-editor.html#manage_cookies)。 这样您就可以避免手动从  `http-client.cookies` 文件中删除不需要的 cookies。

* 在请求之前，添加带有  `@no-cookie-jar`  标记的注释行。

```HTTP_REQUEST_FULL
// @no-cookie-jar
GET example.com/api

```

Procedure: 禁用编码

默认情况下，HTTP 客户端会将请求参数和正文编码为 ASCII 格式。 例如，请求形参中的斜杠字符将作为  `%2F`  发送。 您可以禁用编码以按原样发送请求。

* 在请求之前，添加带有  `@no-auto-encoding`  标记的注释行。

编码已禁用:

使用该标签时，请求参数和正文不会被编码：

```HTTP_REQUEST_FULL
# @no-auto-encoding
GET https://examples.com/api?
            name=@#$somebody&
            qwerty=%40%23%24

```

生成的请求将按原样发送：

```HTTP_REQUEST_FULL
https://examples.com/api?name=@#$somebody&qwerty=%40%23%24

```

编码已启用:

默认情况下，如果未使用该标签，编码将被启用。

```HTTP_REQUEST_FULL
### Default behavior
GET https://examples.com/api?
            name=@#$somebody&
            qwerty=%40%23%24

```

在此请求中，参数将被编码：

```HTTP_REQUEST_FULL
https://examples.com/api?name=%40%23%24somebody&qwerty=%40%23%24

```

Procedure: 自定义 HTTP 请求超时

HTTP 客户端 在与服务器建立连接时有 60 秒的超时，同时在持续连接中等待新数据包也有 60 秒的超时。 您可以自定义这两个超时。

* 要为已建立的连接中的新数据包设置超时时间，请在请求前添加带有  `@timeout` 标签的注释行。

```HTTP_REQUEST_FULL
# @timeout 600
GET example.com/api

```

* 要设置连接超时，请在请求前添加带有  `@connection-timeout`  标签的注释行。

```HTTP_REQUEST_FULL
// @connection-timeout 2 m
GET example.com/api

```

默认情况下，超时值以秒为单位，但您可以在值后添加明确的时间单位：  `毫秒`  为毫秒，  `秒`  为秒，  `m`  为分钟，例如  `100 毫秒`  或  `5 m` 。

> **Note:**
> 还可以使用虚拟机选项（  `帮助 | 编辑自定义 VM 选项` ）在 IDE 级别更改这些超时。
>
>
>
> * `-Didea.connection.timeout` 配置连接超时（默认以毫秒为单位）。 在单个 HTTP 请求中， `@connection-timeout` 属性会覆盖它。
>
> * `-Didea.read.timeout` 配置新数据包的超时（默认以毫秒为单位）。 在单个 HTTP 请求中， `@timeout` 属性会覆盖它。
>
>
>
> 请注意，虚拟机选项会影响整个应用程序中 IntelliJ IDEA 的行为。 这些超时不仅适用于使用 HTTP 客户端发出的 HTTP 请求，还适用于 IntelliJ IDEA 在与网络交互时可能发送的所有 HTTP 请求，例如访问外部服务时。

## 处理响应

您可以使用 JavaScript 处理响应。 在请求后输入  `>` 字符并指定 JavaScript 文件的路径和名称，或将响应处理程序脚本代码包装在  `{% ... %}` 中。

```HTTP_REQUEST_FULL
GET https://httpbin.org/get

> /path/to/responseHandler.js

```

```HTTP_REQUEST_FULL
GET https://httpbin.org/get

> {%
    client.global.set("my_cookie", response.headers.valuesOf("Set-Cookie")[0]);
%}

```

有关更多信息，请参见 [HTTP Response 处理 API 参考](http-response-handling-api-reference.html)。

## 重定向响应

您可以将响应重定向到文件。 如果文件已存在，请使用  `>>`  创建一个带有后缀的新文件，并使用  `>>!`  重写该文件。 您可以指定绝对路径或相对于当前 HTTP 请求 文件的相对路径。 您还可以在路径中使用变量，包括环境变量和以下预定义变量：

* `{{$projectRoot}}` 指向项目根目录

* `{{$historyFolder}}` 指向 `.idea/httpRequests/`

以下示例 HTTP 请求在 HTTP 请求 文件旁边在  `myFolder` 中创建  `myFile.json` ，并将响应重定向到它。 如果文件已经存在，它会创建  `myFile-1.json` 。

```HTTP_REQUEST
POST https://httpbin.org/post
Content-Type: application/json

{
  "id": 999,
  "value": "content"
}

>> myFolder/myFile.json
        
```

以下示例 HTTP 请求在  `myFile.json`  中创建  `.idea/httpRequests/` 。 如果文件已存在，它会覆盖文件。 它也会用位于项目根目录的  `handler.js` 脚本 [处理响应](#response-handling)。

```HTTP_REQUEST
POST https://httpbin.org/post
Content-Type: application/json

{
  "id": 999,
  "value": "content"
}

> {{$projectRoot}}/handler.js

>>! {{$historyFolder}}/myFile.json
        
```

> **Note:**
> 对于 Windows，请使用反斜杠  `\`  指定路径。

