Getting started with ESP32 HTTP

1. Environmental preparation

You can first understand the following knowledge:

  • The difference between HTTP request method get and post

    Url describes a resource on the network, and get, post, put and delete correspond to four operations: query, change, add and delete.

    • Get is used to get data information from the server
    • post is used to send data information to the server
      • post request mode - the main feature is to put the request data on the body
        • x-www-form-urlencoded: application/x-www-from-urlencoded, which converts the data in the form into key value pairs
        • Raw: the data of txt, JSON, XML and html can be transmitted through raw
        • Form data: multipart / form data type corresponding to content type. You can send key value pairs or pass file parameters.
        • binary: used to send file content requests.
  • Response status code category

    • 1xx indication - indicates that the request has been received and continues processing
    • 2xx successful – indicates that the request has been successfully received, understood and accepted
    • 3xx redirection - incomplete information needs to be further supplemented
    • 4xx client error - the request has syntax errors or the request cannot be implemented
    • 5xx server side error - the server failed to implement the legal request

Commonly seen status codes:

  • 200 - the request is successful and has been processed normally
  • The requested URL does not exist on the server side
  • 502 - server internal error, unable to complete request

For detailed documentation:

2. ESP32 demo verification

use esp-idf/examples/protocols/esp_http_client To test.

void app_main(void)
{
    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
      ESP_ERROR_CHECK(nvs_flash_erase());
      ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK(ret);
    ESP_ERROR_CHECK(esp_netif_init());
    ESP_ERROR_CHECK(esp_event_loop_create_default());

    /* This helper function configures Wi-Fi or Ethernet, as selected in menuconfig.
     * Read "Establishing Wi-Fi or Ethernet Connection" section in
     * examples/protocols/README.md for more information about this function.
     */
    ESP_ERROR_CHECK(example_connect());
    ESP_LOGI(TAG, "Connected to AP, begin http example");

    xTaskCreate(&http_test_task, "http_test_task", 8192, NULL, 5, NULL);
}
static void http_test_task(void *pvParameters)
{
    http_rest_with_url();
    ESP_LOGI(TAG, "Finish http example");
    vTaskDelete(NULL);
}
static void http_rest_with_url(void)
{
    char local_response_buffer[MAX_HTTP_OUTPUT_BUFFER] = {0};
    /**
     * NOTE: All the configuration parameters for http_client must be spefied either in URL or as host and path parameters.
     * If host and path parameters are not set, query parameter will be ignored. In such cases,
     * query parameter should be specified in URL.
     *
     * If URL as well as host and path parameters are specified, values of host and path will be considered.
     */
    esp_http_client_config_t config = {
        .host = "httpbin.org",
        .path = "/get",
        // .query = "esp",
        .event_handler = _http_event_handler,
        .user_data = local_response_buffer,        // Pass address of local buffer to get response
        .disable_auto_redirect = true,
    };
    esp_http_client_handle_t client = esp_http_client_init(&config);

    // GET
    esp_err_t err = esp_http_client_perform(client);
    if (err == ESP_OK) {
        ESP_LOGI(TAG, "HTTP GET Status = %d, content_length = %d",
                esp_http_client_get_status_code(client),
                esp_http_client_get_content_length(client));
    } else {
        ESP_LOGE(TAG, "HTTP GET request failed: %s", esp_err_to_name(err));
    }
    ESP_LOG_BUFFER_HEX(TAG, local_response_buffer, strlen(local_response_buffer));

    char *buffer = malloc(MAX_HTTP_RECV_BUFFER + 1);
    if (buffer == NULL) {
        ESP_LOGE(TAG, "Cannot malloc http receive buffer");
        return;
    }

    if ((err = esp_http_client_open(client, 0)) != ESP_OK) {
        ESP_LOGE(TAG, "Failed to open HTTP connection: %s", esp_err_to_name(err));
        free(buffer);
        return;
    }
    int content_length =  esp_http_client_fetch_headers(client);
    int total_read_len = 0, read_len;
    if (total_read_len < content_length && content_length <= MAX_HTTP_RECV_BUFFER) {
        read_len = esp_http_client_read(client, buffer, content_length);
        if (read_len <= 0) {
            ESP_LOGE(TAG, "Error read data");
        }
        buffer[read_len] = 0;
        ESP_LOGI(TAG, "read_len = %d,data: %.*s", read_len,read_len,buffer);
    }

    // POST
    const char *post_data = "{\"field1\":\"value1\"}";
    esp_http_client_set_url(client, "http://httpbin.org/post");
    esp_http_client_set_method(client, HTTP_METHOD_POST);
    esp_http_client_set_header(client, "Content-Type", "application/json");
    esp_http_client_set_post_field(client, post_data, strlen(post_data));
    err = esp_http_client_perform(client);
    if (err == ESP_OK) {
        char *buffer1 = malloc(MAX_HTTP_RECV_BUFFER + 1);
        esp_http_client_get_post_field(client, &buffer1);
        ESP_LOGI(TAG, "HTTP POST Status = %d, content_length = %d, buffer1: %s", 
                esp_http_client_get_status_code(client),
                esp_http_client_get_content_length(client), buffer1);
    } else {
        ESP_LOGE(TAG, "HTTP POST request failed: %s", esp_err_to_name(err));
    }

You can get the data format of the get request and print it out. The screenshot below shows:

3. Precautions:

  1. URL redirection

    This is because esp cannot automatically redirect URL s like a Web browser.
    The most likely explanation is that the Web server did not send Bin file, but sent other contents. Application image The first byte of the bin file should be 0xE9. This error indicates that the first character 0x3C of the file is ASCII "<", and indicates that the server is sending an HTML page instead of Bin file.

    You can try to put the same URL into tools such as curl on the command line and download it in this way Is the bin file downloaded or something else (such as an error page, login page, or redirect page).

  2. If there is no way to successfully obtain the correct response from the http server. At this point, you need to check the set through the postman or postjason tool_ Header sets whether the header is assembled correctly and whether the data is sent according to the standard header format on the server side.
    If you still can't find the problem, you need to check the http packet by grabbing the packet card (wireshark, etc.) to see whether the device does not send the correct format or the server does not respond.

Keywords: Front-end http PostMan

Added by halfman on Wed, 02 Feb 2022 21:19:26 +0200