# ESP HTTP 客户端

[English]

## 概述

`esp_http_client` 提供了一组 API，用于从 ESP-IDF 应用程序中发起 HTTP/S 请求，具体的使用步骤如下：

> - 首先调用 `esp_http_client_init()`，创建一个 `esp_http_client_handle_t` 实例，即基于给定的 `esp_http_client_config_t` 配置创建 HTTP 客户端句柄。此函数必须第一个被调用。若用户未明确定义参数的配置值，则使用默认值。

> - 其次调用 `esp_http_client_perform()`，执行 `esp_http_client` 的所有操作，包括打开连接、交换数据、关闭连接（如需要），同时在当前任务完成前阻塞该任务。所有相关的事件（在 `esp_http_client_config_t` 中指定）将通过事件处理程序被调用。

> - 最后调用 `esp_http_client_cleanup()` 来关闭连接（如有），并释放所有分配给 HTTP 客户端实例的内存。此函数必须在操作完成后最后一个被调用。

## 应用示例

protocols/esp_http_client 演示了如何使用 ESP HTTP 客户端发起 HTTP/S 请求。

## HTTP 基本请求

如需了解实现细节，请参考应用示例中的 `http_rest_with_url` 和 `http_rest_with_hostname_path` 函数。

## 持久连接

持久连接是 HTTP 客户端在多次交换中重复使用同一连接的方法。如果服务器没有使用 `Connection: close` 头来请求关闭连接，连接就会一直保持开放，用于其他新请求。

为了使 ESP HTTP 客户端充分利用持久连接的优势，建议尽可能多地使用同一个句柄实例来发起请求，可参考应用示例中的函数 `http_rest_with_url` 和 `http_rest_with_hostname_path`。示例中，一旦创建连接，即会在连接关闭前发出多个请求（如 `GET`、 `POST`、 `PUT` 等）。

### 为 TLS 使用安全元件 (ATECC608)

安全元件 (ATECC608) 也可用于 HTTP 客户端连接中的底层 TLS 连接。详细内容请参考 ESP-TLS 文档 中的 ESP-TLS 中的 ATECC608A（安全元件）支持 小节。如需支持安全元素，必须首先在 menuconfig 中通过 CONFIG_ESP_TLS_USE_SECURE_ELEMENT 对其进行启用，此后，可配置 HTTP 客户端使用安全元素，如下所示：

    esp_http_client_config_t cfg = {
        /* other configurations options */
        .use_secure_element = true,
    };

## HTTPS 请求

ESP HTTP 客户端支持使用 mbedTLS 的 SSL 连接，需将 `url` 配置为以 `https` 开头，或将 `transport_type` 设置为 `HTTP_TRANSPORT_OVER_SSL`。可以通过 CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS 来配置 HTTPS 支持（默认启用）。

备注

在发起 HTTPS 请求时，如需服务器验证，首先需要向 `esp_http_client_config_t` 配置中的 `cert_pem` 成员提供额外的根证书（PEM 格式）。用户还可以通过 `esp_http_client_config_t` 配置中的 `crt_bundle_attach` 成员，使用 `ESP x509 Certificate Bundle` 进行服务器验证。

如需了解上文备注中的实现细节，请参考应用示例中的函数 `https_with_url` 和 `https_with_hostname_path`。

## HTTP 流

有些应用程序需要主动打开连接并控制数据交换（数据流）。在这种情况下，应用流程与常规请求不同。请参考以下示例：

> - `esp_http_client_init()`：创建一个 HTTP 客户端句柄。

> - `esp_http_client_set_*` 或 `esp_http_client_delete_*`：修改 HTTP 连接参数（可选）。

> - `esp_http_client_open()`：用 `write_len` （该参数为需要写入服务器的内容长度）打开 HTTP 连接，设置 `write_len=0` 为只读连接。

> - `esp_http_client_write()`：向服务器写入数据，最大长度为 `esp_http_client_open()` 函数中的 `write_len` 值；配置 `write_len=0` 无需调用此函数。

> - `esp_http_client_fetch_headers()`：在发送完请求头和服务器数据（如有）后，读取 HTTP 服务器的响应头。从服务器返回 `content-length`，并可以由 `esp_http_client_get_status_code()` 继承，以获取连接的 HTTP 状态。

> - `esp_http_client_read()`：读取 HTTP 流。

> - `esp_http_client_close()`：关闭连接。

> - `esp_http_client_cleanup()`：释放分配的资源。

如需了解实现细节，请参考应用示例中的函数 `http_perform_as_stream_reader`。

## HTTP 认证

ESP HTTP 客户端同时支持 基本 和 摘要 认证。

  - 用户可以在 `url` 或 `esp_http_client_config_t` 配置中的 `username` 和 `password` 处输入用户名和密码。对于 `auth_type = HTTP_AUTH_TYPE_BASIC`，HTTP 客户端只需执行一项操作就可通过认证过程。

  - 如果 `auth_type = HTTP_AUTH_TYPE_NONE`，但配置中有 `username` 和 `password` 字段，HTTP 客户端需要执行两项操作。客户端在第一次尝试连接服务器时，会收到 `401 Unauthorized` 头，而后再根据这些信息来选择认证方法，并在第二项操作中执行。

  - 如需了解实现细节，请参考应用示例中的函数 `http_auth_basic`、 `http_auth_basic_redirect` （用于基本认证）和 `http_auth_digest` （用于摘要认证）。

  - 目前，摘要认证仅支持 MD5 和 SHA-256 算法。

### 认证配置示例

> - 基于 URI 的认证

>   >     esp_http_client_config_t config = {
>   >         .url = "http://user:passwd@httpbin.org/basic-auth/user/passwd",
>   >         .auth_type = HTTP_AUTH_TYPE_BASIC,
>   >     };

> - 基于用户名和密码的认证

>   >     esp_http_client_config_t config = {
>   >         .url = "http://httpbin.org/basic-auth/user/passwd",
>   >         .username = "user",
>   >         .password = "passwd",
>   >         .auth_type = HTTP_AUTH_TYPE_BASIC,
>   >     };

## 响应头访问

ESP HTTP 客户端具有保存和检索来自服务器的 HTTP 响应头的功能。当应用程序需要访问元数据（如内容类型、缓存控制指令、自定义服务器头或其他响应信息）时，此功能会发挥重要作用。

### 配置

要启用响应头保存功能，必须配置以下 Kconfig 选项：

> - CONFIG_ESP_HTTP_CLIENT_SAVE_RESPONSE_HEADERS：启用响应头保存（默认禁用以节省内存）。

> - CONFIG_ESP_HTTP_CLIENT_MAX_SAVED_RESPONSE_HEADERS：要保存的响应头的最大数量（默认值：10）。

> - CONFIG_ESP_HTTP_CLIENT_MAX_RESPONSE_HEADER_SIZE：响应头键和值的最大大小（单位：字节，默认值：各 128 字节）。

### 用法

启用后，在执行 HTTP 请求后，可以使用 `esp_http_client_get_response_header()` 函数检索响应头。该函数返回给定键对应响应头的值。

示例：

    #if CONFIG_ESP_HTTP_CLIENT_SAVE_RESPONSE_HEADERS
    esp_http_client_handle_t client = esp_http_client_init(&config);
    esp_err_t err = esp_http_client_perform(client);

    if (err == ESP_OK) {
        char *content_type = NULL;
        err = esp_http_client_get_response_header(client, "Content-Type", &content_type);
        if (err == ESP_OK && content_type != NULL) {
            ESP_LOGI(TAG, "Content-Type: %s", content_type);
        } else if (err == ESP_ERR_NOT_FOUND) {
            ESP_LOGW(TAG, "Content-Type header not found");
        }

        char *date = NULL;
        err = esp_http_client_get_response_header(client, "Date", &date);
        if (err == ESP_OK && date != NULL) {
            ESP_LOGI(TAG, "Date: %s", date);
        }
    }

    esp_http_client_cleanup(client);
    #endif

### 重要限制

使用响应头访问功能时，需注意以下限制：

> - 响应头数量限制：仅保存前 `CONFIG_ESP_HTTP_CLIENT_MAX_SAVED_RESPONSE_HEADERS` 个响应头，超出限制的响应头会被丢弃，并产生警告日志。

> - 大小限制：若响应头的键或值长度超过 `CONFIG_ESP_HTTP_CLIENT_MAX_RESPONSE_HEADER_SIZE` 字节，该头将被丢弃，并记录包含实际长度的警告日志。

> - 多值响应头：对于在响应中出现多次的响应头（如 `Set-Cookie`），仅保存最后一次出现的值。

> - 大小写敏感性：查找响应头时不区分大小写，但存储时会保留原始大小写。

> - 内存开销：启用此功能会增加内存消耗。每个客户端实例的近似内存使用量为 `(CONFIG_ESP_HTTP_CLIENT_MAX_SAVED_RESPONSE_HEADERS * CONFIG_ESP_HTTP_CLIENT_MAX_RESPONSE_HEADER_SIZE * 2)` 字节。

> - 响应头生命周期：当通过 `esp_http_client_perform()` 或 `esp_http_client_prepare()` 用同一客户端句柄发起新请求时，保存的响应头会被清空。

备注

返回的头值指针由 HTTP 客户端内部管理，应用程序不得释放该指针。该指针在客户端句柄被清理或启动新请求之前保持有效。

## 事件处理

ESP HTTP 客户端支持事件处理，发生相关事件时会触发相应的事件处理程序。`esp_http_client_event_id_t` 中包含了所有使用 ESP HTTP 客户端执行 HTTP 请求时可能发生的事件。

通过 `esp_http_client_config_t::event_handler` 设置回调函数即可启用事件处理功能。

也可以在客户端初始化后使用 `esp_http_client_set_event_handler()` 函数设置回调函数。

## ESP HTTP 客户端诊断信息

诊断信息可以帮助用户深入了解出现的问题。在 ESP HTTP 客户端中，可以通过在 事件循环库 中注册事件处理程序来获取诊断信息。此功能的增加基于 ESP Insights 框架，该框架可帮助收集诊断信息。然而，即使不依赖 ESP Insights 框架，也可以获取诊断信息。事件处理程序可通过 `esp_event_handler_register()` 函数注册到事件循环中。

事件循环中不同 HTTP 客户端事件的预期数据类型如下所示：

> - HTTP_EVENT_ERROR : `esp_http_client_handle_t`

> - HTTP_EVENT_ON_CONNECTED : `esp_http_client_handle_t`

> - HTTP_EVENT_HEADERS_SENT : `esp_http_client_handle_t`

> - HTTP_EVENT_ON_HEADER : `esp_http_client_handle_t`

> - HTTP_EVENT_ON_HEADERS_COMPLETE: `esp_http_client_handle_t`

> - HTTP_EVENT_ON_STATUS_CODE : `esp_http_client_handle_t`

> - HTTP_EVENT_ON_DATA : `esp_http_client_on_data_t`

> - HTTP_EVENT_ON_FINISH : `esp_http_client_handle_t`

> - HTTP_EVENT_DISCONNECTED : `esp_http_client_handle_t`

> - HTTP_EVENT_REDIRECT : `esp_http_client_redirect_event_data_t`

在无法接收到 `HTTP_EVENT_DISCONNECTED` 之前，与事件数据一起接收到的 `esp_http_client_handle_t` 将始终有效。这个句柄主要是为了区分不同的客户端连接，无法用于其他目的，因为它可能会随着客户端连接状态的变化而改变。

## TLS 协议版本

可在 `esp_http_client_config_t` 中设置用于底层 TLS 连接的 TLS 协议版本。了解更多信息，请参考 ESP-TLS 中的 TLS 协议版本 章节。

HTTP 客户端的 TLS 协议版本可按如下方式配置：

>     #include "esp_http_client.h"
>     esp_http_client_config_t config = {
>         .tls_version = ESP_HTTP_CLIENT_TLS_VER_TLS_1_2,
>     };

## API 参考

### Header File

- components/esp_http_client/include/esp_http_client.h

- This header file can be included with:

  >     #include "esp_http_client.h"

- This header file is a part of the API provided by the `esp_http_client` component. To declare that your component depends on `esp_http_client`, add the following to your CMakeLists.txt:

  >     REQUIRES esp_http_client

  > or

  >     PRIV_REQUIRES esp_http_client

### Functions

esp_http_client_handle_t esp_http_client_init(const esp_http_client_config_t *config)

  Start a HTTP session This function must be the first function to call, and it returns a esp_http_client_handle_t that you must use as input to other functions in the interface. This call MUST have a corresponding call to esp_http_client_cleanup when the operation is complete.

  参数:

    config -- [in] The configurations, see `http_client_config_t`

  返回:

    - `esp_http_client_handle_t`

    - NULL if any errors

esp_err_t esp_http_client_perform(esp_http_client_handle_t client)

  Invoke this function after `esp_http_client_init` and all the options calls are made, and will perform the transfer as described in the options. It must be called with the same esp_http_client_handle_t as input as the esp_http_client_init call returned. esp_http_client_perform performs the entire request in either blocking or non-blocking manner. By default, the API performs request in a blocking manner and returns when done, or if it failed, and in non-blocking manner, it returns if EAGAIN/EWOULDBLOCK or EINPROGRESS is encountered, or if it failed. And in case of non-blocking request, the user may call this API multiple times unless request & response is complete or there is a failure. To enable non-blocking esp_http_client_perform(), `is_async` member of esp_http_client_config_t must be set while making a call to esp_http_client_init() API. You can do any amount of calls to esp_http_client_perform while using the same esp_http_client_handle_t. The underlying connection may be kept open if the server allows it. If you intend to transfer more than one file, you are even encouraged to do so. esp_http_client will then attempt to reuse the same connection for the following transfers, thus making the operations faster, less CPU intense and using less network resources. Just note that you will have to use `esp_http_client_set_**` between the invokes to set options for the following esp_http_client_perform.

  备注

  You must never call this function simultaneously from two places using the same client handle. Let the function return first before invoking it another time. If you want parallel transfers, you must use several esp_http_client_handle_t. This function include `esp_http_client_open` -> `esp_http_client_write` -> `esp_http_client_fetch_headers` -> `esp_http_client_read` (and option) `esp_http_client_close`.

  参数:

    client -- The esp_http_client handle

  返回:

    - ESP_OK on successful

    - ESP_FAIL on error

    - ESP_ERR_HTTP_CONNECTING is timed-out before connection is made

    - ESP_ERR_HTTP_WRITE_DATA is timed-out before request fully sent

    - ESP_ERR_HTTP_EAGAIN is timed-out before any data was ready

    - ESP_ERR_HTTP_READ_TIMEOUT if read operation times out

    - ESP_ERR_HTTP_INCOMPLETE_DATA if read operation returns less data than expected

    - ESP_ERR_HTTP_CONNECTION_CLOSED if server closes the connection

esp_err_t esp_http_client_prepare(esp_http_client_handle_t client)

  Prepare HTTP client for a new request This function initializes the client state and prepares authentication if needed. It should be called before sending a request.

  参数:

    client -- [in] The esp_http_client handle

  返回:

    - ESP_OK on successful

    - ESP_FAIL on error

esp_err_t esp_http_client_request_send(esp_http_client_handle_t client, int write_len)

  Send HTTP request headers and data This function sends the HTTP request line, headers, and any post data to the server.

  参数:

    - client -- [in] The esp_http_client handle

    - write_len -- [in] Length of data to write (for POST/PUT requests)

  返回:

    - ESP_OK on successful

    - ESP_FAIL on error

    - ESP_ERR_HTTP_WRITE_DATA if write operation fails

esp_err_t esp_http_client_cancel_request(esp_http_client_handle_t client)

  Cancel an ongoing HTTP request. This API closes the current socket and opens a new socket with the same esp_http_client context.

  参数:

    client -- The esp_http_client handle

  返回:

    - ESP_OK on successful

    - ESP_FAIL on error

    - ESP_ERR_INVALID_ARG

    - ESP_ERR_INVALID_STATE

esp_err_t esp_http_client_set_url(esp_http_client_handle_t client, const char *url)

  Set URL for client, when performing this behavior, the options in the URL will replace the old ones.

  参数:

    - client -- [in] The esp_http_client handle

    - url -- [in] The url

  返回:

    - ESP_OK

    - ESP_FAIL

esp_err_t esp_http_client_set_post_field(esp_http_client_handle_t client, const char *data, int len)

  Set post data, this function must be called before `esp_http_client_perform`. Note: Post data persists between requests and must be cleared manually. To avoid post data carryover, set the post data to NULL before starting any subsequent requests.

  参数:

    - client -- [in] The esp_http_client handle

    - data -- [in] post data pointer

    - len -- [in] post length

  返回:

    - ESP_OK

    - ESP_FAIL

int esp_http_client_get_post_field(esp_http_client_handle_t client, char **data)

  Get current post field information.

  参数:

    - client -- [in] The client

    - data -- [out] Point to post data pointer

  返回:

    Size of post data

esp_err_t esp_http_client_set_header(esp_http_client_handle_t client, const char *key, const char *value)

  Set http request header, this function must be called after esp_http_client_init and before any perform function.

  参数:

    - client -- [in] The esp_http_client handle

    - key -- [in] The header key

    - value -- [in] The header value

  返回:

    - ESP_OK

    - ESP_FAIL

esp_err_t esp_http_client_get_header(esp_http_client_handle_t client, const char *key, char **value)

  Get http request header. The value parameter will be set to NULL if there is no header which is same as the key specified, otherwise the address of header value will be assigned to value parameter. This function must be called after `esp_http_client_init`.

  参数:

    - client -- [in] The esp_http_client handle

    - key -- [in] The header key

    - value -- [out] The header value

  返回:

    - ESP_OK: Header found

    - ESP_ERR_INVALID_ARG: Invalid arguments

    - ESP_ERR_NOT_FOUND: Header not found

esp_err_t esp_http_client_get_response_header(esp_http_client_handle_t client, const char *key, char **value)

  Get a response header value by key The value parameter will be set to NULL if there is no header which is same as the key specified, otherwise the address of header value will be assigned to value parameter. This function must be called after `esp_http_client_init`.

  备注

  Limitations:

  - Only first CONFIG_ESP_HTTP_CLIENT_MAX_SAVED_RESPONSE_HEADERS (default: 10) headers are saved

  - Headers exceeding CONFIG_ESP_HTTP_CLIENT_MAX_RESPONSE_HEADER_SIZE (default: 128) bytes are discarded

  - Multi-value headers (e.g., Set-Cookie) only retain the last value

  - Headers are case-insensitive for lookup but case-preserving for storage

  参数:

    - client -- [in] The esp_http_client handle

    - key -- [in] The header key

    - value -- [out] Pointer to store the header value. This pointer should not be freed by the user.

  返回:

    - ESP_OK: Header found

    - ESP_ERR_INVALID_ARG: Invalid arguments

    - ESP_ERR_NOT_FOUND: Header not found

esp_err_t esp_http_client_get_username(esp_http_client_handle_t client, char **value)

  Get http request username. The address of username buffer will be assigned to value parameter. This function must be called after `esp_http_client_init`.

  参数:

    - client -- [in] The esp_http_client handle

    - value -- [out] The username value

  返回:

    - ESP_OK

    - ESP_ERR_INVALID_ARG

esp_err_t esp_http_client_set_username(esp_http_client_handle_t client, const char *username)

  Set http request username. The value of username parameter will be assigned to username buffer. If the username parameter is NULL then username buffer will be freed.

  参数:

    - client -- [in] The esp_http_client handle

    - username -- [in] The username value

  返回:

    - ESP_OK

    - ESP_ERR_INVALID_ARG

esp_err_t esp_http_client_get_password(esp_http_client_handle_t client, char **value)

  Get http request password. The address of password buffer will be assigned to value parameter. This function must be called after `esp_http_client_init`.

  参数:

    - client -- [in] The esp_http_client handle

    - value -- [out] The password value

  返回:

    - ESP_OK

    - ESP_ERR_INVALID_ARG

esp_err_t esp_http_client_set_password(esp_http_client_handle_t client, const char *password)

  Set http request password. The value of password parameter will be assigned to password buffer. If the password parameter is NULL then password buffer will be freed.

  参数:

    - client -- [in] The esp_http_client handle

    - password -- [in] The password value

  返回:

    - ESP_OK

    - ESP_ERR_INVALID_ARG

esp_err_t esp_http_client_set_authtype(esp_http_client_handle_t client, esp_http_client_auth_type_t auth_type)

  Set http request auth_type.

  参数:

    - client -- [in] The esp_http_client handle

    - auth_type -- [in] The esp_http_client auth type

  返回:

    - ESP_OK

    - ESP_ERR_INVALID_ARG

esp_err_t esp_http_client_get_user_data(esp_http_client_handle_t client, void **data)

  Get http request user_data. The value stored from the esp_http_client_config_t will be written to the address passed into data.

  参数:

    - client -- [in] The esp_http_client handle

    - data -- [out] A pointer to the pointer that will be set to user_data.

  返回:

    - ESP_OK

    - ESP_ERR_INVALID_ARG

esp_err_t esp_http_client_set_user_data(esp_http_client_handle_t client, void *data)

  Set http request user_data. The value passed in +data+ will be available during event callbacks. No memory management will be performed on the user's behalf.

  参数:

    - client -- [in] The esp_http_client handle

    - data -- [in] The pointer to the user data

  返回:

    - ESP_OK

    - ESP_ERR_INVALID_ARG

esp_err_t esp_http_client_set_event_handler(esp_http_client_handle_t client, http_event_handle_cb event_handler)

  Set the event handler for the client.

  参数:

    - client -- [in] The esp_http_client handle

    - event_handler -- [in] The event handler

  返回:

    - ESP_OK

    - ESP_ERR_INVALID_ARG

int esp_http_client_get_errno(esp_http_client_handle_t client)

  Get HTTP client session errno.

  参数:

    client -- [in] The esp_http_client handle

  返回:

    - (-1) if invalid argument

    - errno

esp_err_t esp_http_client_get_and_clear_last_tls_error(esp_http_client_handle_t client, int *esp_tls_error_code, int *esp_tls_flags)

  Returns last error in esp_tls with detailed mbedtls related error codes. The error information is cleared internally upon return.

  参数:

    - client -- [in] The esp_http_client handle

    - esp_tls_error_code -- [out] last error code returned from mbedtls api (set to zero if none) This pointer could be NULL if caller does not care about esp_tls_code

    - esp_tls_flags -- [out] last certification verification flags (set to zero if none) This pointer could be NULL if caller does not care about esp_tls_code

  返回:

    - ESP_FAIL if invalid parameters

    - ESP_OK (0) if no error occurred

    - specific error code (based on ESP_ERR_ESP_TLS_BASE) otherwise

esp_err_t esp_http_client_set_method(esp_http_client_handle_t client, esp_http_client_method_t method)

  Set http request method.

  参数:

    - client -- [in] The esp_http_client handle

    - method -- [in] The method

  返回:

    - ESP_OK

    - ESP_ERR_INVALID_ARG

esp_err_t esp_http_client_set_timeout_ms(esp_http_client_handle_t client, int timeout_ms)

  Set http request timeout.

  参数:

    - client -- [in] The esp_http_client handle

    - timeout_ms -- [in] The timeout value

  返回:

    - ESP_OK

    - ESP_ERR_INVALID_ARG

esp_err_t esp_http_client_delete_header(esp_http_client_handle_t client, const char *key)

  Delete http request header.

  参数:

    - client -- [in] The esp_http_client handle

    - key -- [in] The key

  返回:

    - ESP_OK

    - ESP_FAIL

esp_err_t esp_http_client_delete_all_headers(esp_http_client_handle_t client)

  Delete all http request headers.

  参数:

    client -- [in] The esp_http_client handle

  返回:

    - ESP_OK

    - ESP_FAIL

esp_err_t esp_http_client_open(esp_http_client_handle_t client, int write_len)

  This function will be open the connection, write all header strings and return.

  参数:

    - client -- [in] The esp_http_client handle

    - write_len -- [in] HTTP Content length need to write to the server

  返回:

    - ESP_OK

    - ESP_FAIL

    - ESP_ERR_HTTP_CONNECTING if timed-out before connection is made

int esp_http_client_write(esp_http_client_handle_t client, const char *buffer, int len)

  This function will write data to the HTTP connection previously opened by esp_http_client_open()

  参数:

    - client -- [in] The esp_http_client handle

    - buffer -- The buffer

    - len -- [in] This value must not be larger than the write_len parameter provided to esp_http_client_open()

  返回:

    - (-1) if any errors

    - Length of data written

int64_t esp_http_client_fetch_headers(esp_http_client_handle_t client)

  This function need to call after esp_http_client_open, it will read from http stream, process all receive headers.

  参数:

    client -- [in] The esp_http_client handle

  返回:

    - (0) if stream doesn't contain content-length header, or chunked encoding (checked by `esp_http_client_is_chunked_response`)

    - (-1: ESP_FAIL) if any errors

    - (-ESP_ERR_HTTP_EAGAIN = -0x7007) if call is timed-out before any data was ready

    - Download data length defined by content-length header

bool esp_http_client_is_chunked_response(esp_http_client_handle_t client)

  Check response data is chunked.

  参数:

    client -- [in] The esp_http_client handle

  返回:

    true or false

int esp_http_client_read(esp_http_client_handle_t client, char *buffer, int len)

  Read data from http stream.

  备注

  (-ESP_ERR_HTTP_EAGAIN = -0x7007) is returned when call is timed-out before any data was ready

  参数:

    - client -- [in] The esp_http_client handle

    - buffer -- The buffer

    - len -- [in] The length

  返回:

    - (-1) if any errors

    - Length of data was read

int esp_http_client_get_status_code(esp_http_client_handle_t client)

  Get http response status code, the valid value if this function invoke after `esp_http_client_perform`

  参数:

    client -- [in] The esp_http_client handle

  返回:

    Status code

int64_t esp_http_client_get_content_length(esp_http_client_handle_t client)

  Get http response content length (from header Content-Length) the valid value if this function invoke after `esp_http_client_perform`

  参数:

    client -- [in] The esp_http_client handle

  返回:

    - (-1) Chunked transfer

    - Content-Length value as bytes

int64_t esp_http_client_get_content_range(esp_http_client_handle_t client)

  Get http response content range (from header Content-Range) The returned value is valid only if this function is invoked after a successful call to `esp_http_client_perform`. Content-Range is set to -1 if parsing fails or if the Content-Range header is not present.

  参数:

    client -- [in] The esp_http_client handle

  返回:

    - Content-Range value as bytes

esp_err_t esp_http_client_close(esp_http_client_handle_t client)

  Close http connection, still kept all http request resources.

  参数:

    client -- [in] The esp_http_client handle

  返回:

    - ESP_OK

    - ESP_FAIL

esp_err_t esp_http_client_clear_response_buffer(esp_http_client_handle_t client)

  Clear cached response buffer (e.g. data received during fetch headers). Use this when reusing the same client handle for a new request after closing the connection, so the next request does not see stale data.

  参数:

    client -- [in] The esp_http_client handle

  返回:

    - ESP_OK

    - ESP_ERR_INVALID_ARG if client is NULL

esp_err_t esp_http_client_cleanup(esp_http_client_handle_t client)

  This function must be the last function to call for an session. It is the opposite of the esp_http_client_init function and must be called with the same handle as input that a esp_http_client_init call returned. This might close all connections this handle has used and possibly has kept open until now. Don't call this function if you intend to transfer more files, re-using handles is a key to good performance with esp_http_client.

  参数:

    client -- [in] The esp_http_client handle

  返回:

    - ESP_OK

    - ESP_FAIL

esp_http_client_transport_t esp_http_client_get_transport_type(esp_http_client_handle_t client)

  Get transport type.

  参数:

    client -- [in] The esp_http_client handle

  返回:

    - HTTP_TRANSPORT_UNKNOWN

    - HTTP_TRANSPORT_OVER_TCP

    - HTTP_TRANSPORT_OVER_SSL

esp_err_t esp_http_client_set_redirection(esp_http_client_handle_t client)

  Set redirection URL. When received the 30x code from the server, the client stores the redirect URL provided by the server. This function will set the current URL to redirect to enable client to execute the redirection request. When `disable_auto_redirect` is set, the client will not call this function but the event `HTTP_EVENT_REDIRECT` will be dispatched giving the user control over the redirection event.

  参数:

    client -- [in] The esp_http_client handle

  返回:

    - ESP_OK

    - ESP_FAIL

esp_err_t esp_http_client_reset_redirect_counter(esp_http_client_handle_t client)

  Reset the redirection counter. This is useful to reset redirect counter in cases where the same handle is used for multiple requests.

  参数:

    client -- [in] The esp_http_client handle

  返回:

    - ESP_OK

    - ESP_ERR_INVALID_ARG

esp_err_t esp_http_client_set_auth_data(esp_http_client_handle_t client, const char *auth_data, int len)

  On receiving a custom authentication header, this API can be invoked to set the authentication information from the header. This API can be called from the event handler.

  参数:

    - client -- [in] The esp_http_client handle

    - auth_data -- [in] The authentication data received in the header

    - len -- [in] length of auth_data.

  返回:

    - ESP_ERR_INVALID_ARG

    - ESP_OK

esp_err_t esp_http_client_add_auth(esp_http_client_handle_t client)

  On receiving HTTP Status code 401, this API can be invoked to add authorization information.

  备注

  There is a possibility of receiving body message with redirection status codes, thus make sure to flush off body data after calling this API.

  参数:

    client -- [in] The esp_http_client handle

  返回:

    - ESP_OK: Successfully added the authentication information.

    - ESP_ERR_INVALID_ARG: Invalid client handle passed.

    - ESP_ERR_NO_MEM: Memory allocation failed for the required fields.

    - ESP_ERR_NOT_SUPPORTED: Unsupported authentication type in the header.

    - ESP_FAIL: Failed to add authentication information due to other reasons.

bool esp_http_client_is_complete_data_received(esp_http_client_handle_t client)

  Checks if entire data in the response has been read without any error.

  参数:

    client -- [in] The esp_http_client handle

  返回:

    - true

    - false

int esp_http_client_read_response(esp_http_client_handle_t client, char *buffer, int len)

  Helper API to read larger data chunks This is a helper API which internally calls `esp_http_client_read` multiple times till the end of data is reached or till the buffer gets full.

  参数:

    - client -- [in] The esp_http_client handle

    - buffer -- The buffer

    - len -- [in] The buffer length

  返回:

    - Length of data was read

esp_err_t esp_http_client_flush_response(esp_http_client_handle_t client, int *len)

  Process all remaining response data This uses an internal buffer to repeatedly receive, parse, and discard response data until complete data is processed. As no additional user-supplied buffer is required, this may be preferable to `esp_http_client_read_response` in situations where the content of the response may be ignored.

  参数:

    - client -- [in] The esp_http_client handle

    - len -- Length of data discarded

  返回:

    - ESP_OK If successful, len will have discarded length

    - ESP_FAIL If failed to read response

    - ESP_ERR_INVALID_ARG If the client is NULL

esp_err_t esp_http_client_get_url(esp_http_client_handle_t client, char *url, const int len)

  Get URL from client.

  参数:

    - client -- [in] The esp_http_client handle

    - url -- [inout] The buffer to store URL

    - len -- [in] The buffer length

  返回:

    - ESP_OK

    - ESP_FAIL

esp_err_t esp_http_client_get_chunk_length(esp_http_client_handle_t client, int *len)

  Get Chunk-Length from client.

  参数:

    - client -- [in] The esp_http_client handle

    - len -- [out] Variable to store length

  返回:

    - ESP_OK If successful, len will have length of current chunk

    - ESP_FAIL If the server is not a chunked server

    - ESP_ERR_INVALID_ARG If the client or len are NULL

esp_http_state_t esp_http_client_get_state(esp_http_client_handle_t client)

  Get the current state of the HTTP client.

  参数:

    client -- [in] The HTTP client handle

  返回:

    Current state of the HTTP client

bool esp_http_client_is_persistent_connection(esp_http_client_handle_t client)

  Check if persistent connection is supported by the server.

  参数:

    client -- [in] The HTTP client handle

  返回:

    true if persistent connection is supported, false otherwise

int esp_http_client_get_socket(esp_http_client_handle_t client)

  Get the socket from the underlying transport.

  参数:

    client -- The HTTP client handle

  返回:

    - -1 if the client is NULL or the transport is not initialized

    - The socket file descriptor if successful

### Structures

struct esp_http_client_event

  HTTP Client events data.

  Public Members

  esp_http_client_event_id_t event_id

    event_id, to know the cause of the event

  esp_http_client_handle_t client

    esp_http_client_handle_t context

  void *data

    data of the event

  int data_len

    data length of data

  void *user_data

    user_data context, from esp_http_client_config_t user_data

  char *header_key

    For HTTP_EVENT_ON_HEADER event_id, it's store current http header key

  char *header_value

    For HTTP_EVENT_ON_HEADER event_id, it's store current http header value

struct esp_http_client_on_data

  Argument structure for HTTP_EVENT_ON_DATA event.

  Public Members

  esp_http_client_handle_t client

    Client handle

  int64_t data_process

    Total data processed

struct esp_http_client_redirect_event_data

  Argument structure for HTTP_EVENT_REDIRECT event.

  Public Members

  esp_http_client_handle_t client

    Client handle

  int status_code

    Status Code

struct esp_http_client_config_t

  HTTP configuration.

  Public Members

  const char *url

    HTTP URL, the information on the URL is most important, it overrides the other fields below, if any

  const char *host

    Domain or IP as string

  int port

    Port to connect, default depend on esp_http_client_transport_t (80 or 443)

  const char *username

    Using for Http authentication

  const char *password

    Using for Http authentication

  esp_http_client_auth_type_t auth_type

    Http authentication type, see `esp_http_client_auth_type_t`

  const char *path

    HTTP Path, if not set, default is `/`

  const char *query

    HTTP query

  const char *cert_pem

    SSL server certification, PEM format as string, if the client requires to verify server

  const char *cert_der

    SSL server certification, DER format as binary, if the client requires to verify server

  size_t cert_len

    Length of the buffer pointed to by cert_pem or cert_der. PEM Certificate - Length of the buffer pointed to by cert_pem. Length should be the length of the certificate including NULL terminator or 0. DER Certificate - Length of the buffer pointed to by cert_der. Should be the length of the certificate.

  const char *client_cert_pem

    SSL client certification, PEM format as string, if the server requires to verify client

  const char *client_cert_der

    SSL client certification, DER format as binary, if the server requires to verify client

  size_t client_cert_len

    Length of the buffer pointed to by client_cert_pem or client_cert_der. PEM Certificate - Length of the buffer pointed to by client_cert_pem. Length should be the length of the certificate including NULL terminator or 0. DER Certificate - Length of the buffer pointed to by client_cert_der. Should be the length of the certificate.

  const char *client_key_pem

    SSL client key, PEM format as string, if the server requires to verify client

  size_t client_key_len

    Length of the buffer pointed to by client_key_pem. May be 0 for null-terminated pem

  const char *client_key_password

    Client key decryption password string

  size_t client_key_password_len

    String length of the password pointed to by client_key_password

  esp_http_client_proto_ver_t tls_version

    TLS protocol version of the connection, e.g., TLS 1.2, TLS 1.3 (default - no preference)

  const char *user_agent

    The User Agent string to send with HTTP requests

  esp_http_client_method_t method

    HTTP Method

  int timeout_ms

    Network timeout in milliseconds. 0 defaults to 5 seconds

  bool disable_auto_redirect

    Disable HTTP automatic redirects

  int max_redirection_count

    Max number of redirections on receiving HTTP redirect status code, using default value if zero

  int max_authorization_retries

    Max connection retries on receiving HTTP unauthorized status code, using default value if zero. Disables authorization retry if -1

  http_event_handle_cb event_handler

    HTTP Event Handle

  esp_http_client_transport_t transport_type

    HTTP transport type, see `esp_http_client_transport_t`

  int buffer_size

    HTTP receive buffer size

  int buffer_size_tx

    HTTP transmit buffer size

  void *user_data

    HTTP user_data context

  bool is_async

    Set asynchronous mode, only supported with HTTPS for now

  bool use_global_ca_store

    Use a global ca_store for all the connections in which this bool is set.

  bool skip_cert_common_name_check

    Skip any validation of server certificate CN field

  const char *common_name

    Pointer to the string containing server certificate common name. If non-NULL, server certificate CN must match this name, If NULL, server certificate CN must match hostname.

  esp_err_t (*crt_bundle_attach)(void *conf)

    Function pointer to esp_crt_bundle_attach. Enables the use of certification bundle for server verification, must be enabled in menuconfig

  bool keep_alive_enable

    Enable keep-alive timeout

  int keep_alive_idle

    Keep-alive idle time. Default is 5 (second)

  int keep_alive_interval

    Keep-alive interval time. Default is 5 (second)

  int keep_alive_count

    Keep-alive packet retry send count. Default is 3 counts

  struct ifreq *if_name

    The name of interface for data to go through. Use the default interface without setting

  const char **alpn_protos

    Application protocols required for HTTP2. If HTTP2/ALPN support is required, a list of protocols that should be negotiated. The format is length followed by protocol name. For the most common cases the following is ok: const char **alpn_protos = { "h2", NULL }; - where 'h2' is the protocol name

  esp_http_client_addr_type_t addr_type

    Address type used in http client configurations

### Macros

DEFAULT_HTTP_BUF_SIZE

ESP_ERR_HTTP_BASE

  Starting number of HTTP error codes

ESP_ERR_HTTP_MAX_REDIRECT

  The error exceeds the number of HTTP redirects

ESP_ERR_HTTP_CONNECT

  Error open the HTTP connection

ESP_ERR_HTTP_WRITE_DATA

  Error write HTTP data

ESP_ERR_HTTP_FETCH_HEADER

  Error read HTTP header from server

ESP_ERR_HTTP_INVALID_TRANSPORT

  There are no transport support for the input scheme

ESP_ERR_HTTP_CONNECTING

  HTTP connection hasn't been established yet

ESP_ERR_HTTP_EAGAIN

  Mapping of errno EAGAIN to esp_err_t

ESP_ERR_HTTP_CONNECTION_CLOSED

  Read FIN from peer and the connection closed

ESP_ERR_HTTP_NOT_MODIFIED

  HTTP 304 Not Modified, no update available

ESP_ERR_HTTP_RANGE_NOT_SATISFIABLE

  HTTP 416 Range Not Satisfiable, requested range in header is incorrect

ESP_ERR_HTTP_READ_TIMEOUT

  HTTP data read timeout

ESP_ERR_HTTP_INCOMPLETE_DATA

  Incomplete data received, less than Content-Length or last chunk

### Type Definitions

typedef struct esp_http_client *esp_http_client_handle_t

typedef struct esp_http_client_event *esp_http_client_event_handle_t

typedef struct esp_http_client_event esp_http_client_event_t

  HTTP Client events data.

typedef struct esp_http_client_on_data esp_http_client_on_data_t

  Argument structure for HTTP_EVENT_ON_DATA event.

typedef struct esp_http_client_redirect_event_data esp_http_client_redirect_event_data_t

  Argument structure for HTTP_EVENT_REDIRECT event.

typedef esp_err_t (*http_event_handle_cb)(esp_http_client_event_t *evt)

### Enumerations

enum esp_http_client_event_id_t

  HTTP Client events id.

  Values:

  enumerator HTTP_EVENT_ERROR

    This event occurs when there are any errors during execution

  enumerator HTTP_EVENT_ON_CONNECTED

    Once the HTTP has been connected to the server, no data exchange has been performed

  enumerator HTTP_EVENT_HEADERS_SENT

    After sending all the headers to the server

  enumerator HTTP_EVENT_HEADER_SENT

    This header has been kept for backward compatibility and will be deprecated in future versions esp-idf

  enumerator HTTP_EVENT_ON_HEADER

    Occurs when receiving each header sent from the server

  enumerator HTTP_EVENT_ON_HEADERS_COMPLETE

    Occurs when all headers are received on the client side

  enumerator HTTP_EVENT_ON_STATUS_CODE

    Occurs when receiving the HTTP status code from the server

  enumerator HTTP_EVENT_ON_DATA

    Occurs when receiving data from the server, possibly multiple portions of the packet

  enumerator HTTP_EVENT_ON_FINISH

    Occurs when complete data is received

  enumerator HTTP_EVENT_DISCONNECTED

    The connection has been disconnected

  enumerator HTTP_EVENT_REDIRECT

    Intercepting HTTP redirects to handle them manually

enum esp_http_client_transport_t

  HTTP Client transport.

  Values:

  enumerator HTTP_TRANSPORT_UNKNOWN

    Unknown

  enumerator HTTP_TRANSPORT_OVER_TCP

    Transport over tcp

  enumerator HTTP_TRANSPORT_OVER_SSL

    Transport over ssl

enum esp_http_client_proto_ver_t

  Values:

  enumerator ESP_HTTP_CLIENT_TLS_VER_ANY
  enumerator ESP_HTTP_CLIENT_TLS_VER_TLS_1_2
  enumerator ESP_HTTP_CLIENT_TLS_VER_TLS_1_3
  enumerator ESP_HTTP_CLIENT_TLS_VER_MAX

enum esp_http_client_ecdsa_curve_t

  ECDSA curve options for TLS connections.

  Values:

  enumerator ESP_HTTP_CLIENT_ECDSA_CURVE_SECP256R1

    Use SECP256R1 curve

  enumerator ESP_HTTP_CLIENT_ECDSA_CURVE_MAX

    to indicate max

enum esp_http_client_method_t

  HTTP method.

  Values:

  enumerator HTTP_METHOD_GET

    HTTP GET Method

  enumerator HTTP_METHOD_POST

    HTTP POST Method

  enumerator HTTP_METHOD_PUT

    HTTP PUT Method

  enumerator HTTP_METHOD_PATCH

    HTTP PATCH Method

  enumerator HTTP_METHOD_DELETE

    HTTP DELETE Method

  enumerator HTTP_METHOD_HEAD

    HTTP HEAD Method

  enumerator HTTP_METHOD_NOTIFY

    HTTP NOTIFY Method

  enumerator HTTP_METHOD_SUBSCRIBE

    HTTP SUBSCRIBE Method

  enumerator HTTP_METHOD_UNSUBSCRIBE

    HTTP UNSUBSCRIBE Method

  enumerator HTTP_METHOD_OPTIONS

    HTTP OPTIONS Method

  enumerator HTTP_METHOD_COPY

    HTTP COPY Method

  enumerator HTTP_METHOD_MOVE

    HTTP MOVE Method

  enumerator HTTP_METHOD_LOCK

    HTTP LOCK Method

  enumerator HTTP_METHOD_UNLOCK

    HTTP UNLOCK Method

  enumerator HTTP_METHOD_PROPFIND

    HTTP PROPFIND Method

  enumerator HTTP_METHOD_PROPPATCH

    HTTP PROPPATCH Method

  enumerator HTTP_METHOD_MKCOL

    HTTP MKCOL Method

  enumerator HTTP_METHOD_REPORT

    HTTP REPORT Method

  enumerator HTTP_METHOD_MAX

enum esp_http_client_auth_type_t

  HTTP Authentication type.

  Values:

  enumerator HTTP_AUTH_TYPE_NONE

    No authention

  enumerator HTTP_AUTH_TYPE_BASIC

    HTTP Basic authentication

  enumerator HTTP_AUTH_TYPE_DIGEST

    HTTP Digest authentication

enum esp_http_client_addr_type_t

  Values:

  enumerator HTTP_ADDR_TYPE_UNSPEC

    Unspecified address family.

  enumerator HTTP_ADDR_TYPE_INET

    IPv4 address family.

  enumerator HTTP_ADDR_TYPE_INET6

    IPv6 address family.

enum esp_http_client_tls_dyn_buf_strategy_t

  Values:

  enumerator HTTP_TLS_DYN_BUF_RX_STATIC

    Strategy to disable dynamic RX buffer allocations and convert to static allocation post-handshake, reducing memory fragmentation

  enumerator HTTP_TLS_DYN_BUF_STRATEGY_MAX

    to indicate max

enum esp_http_state_t

  HTTP Client states.

  Values:

  enumerator HTTP_STATE_UNINIT

    HTTP client uninitialized

  enumerator HTTP_STATE_INIT

    HTTP client initialized

  enumerator HTTP_STATE_CONNECTING

    HTTP client connecting to server

  enumerator HTTP_STATE_CONNECTED

    HTTP client connected to server

  enumerator HTTP_STATE_REQ_COMPLETE_HEADER

    HTTP request headers sent

  enumerator HTTP_STATE_REQ_COMPLETE_DATA

    HTTP request data sent

  enumerator HTTP_STATE_RES_COMPLETE_HEADER

    HTTP response headers received

  enumerator HTTP_STATE_RES_ON_DATA_START

    HTTP response data started

  enumerator HTTP_STATE_RES_COMPLETE_DATA

    HTTP response data completed

  enumerator HTTP_STATE_CLOSE

    HTTP client connection closed

enum HttpStatus_Code

  Enum for the HTTP status codes.

  Values:

  enumerator HttpStatus_Ok
  enumerator HttpStatus_PartialContent
  enumerator HttpStatus_MultipleChoices
  enumerator HttpStatus_MovedPermanently
  enumerator HttpStatus_Found
  enumerator HttpStatus_SeeOther
  enumerator HttpStatus_NotModified
  enumerator HttpStatus_TemporaryRedirect
  enumerator HttpStatus_PermanentRedirect
  enumerator HttpStatus_BadRequest
  enumerator HttpStatus_Unauthorized
  enumerator HttpStatus_Forbidden
  enumerator HttpStatus_NotFound
  enumerator HttpStatus_RangeNotSatisfiable
  enumerator HttpStatus_InternalError

此文档对您有帮助吗？

- 反馈已收到，谢谢！
- 如果您有其他意见，欢迎填写乐鑫文档反馈表。

- 我们重视您的反馈。
- 您可以填写乐鑫文档反馈表告诉我们如何改进该文档。