Client

 

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

public class Client {
 public static void main(String[] args) {
  BufferedWriter bw = null;
  Socket s = null;
  InputStream is = null;
  byte[] buf = new byte[100];
  int len = 0;
  try {
   s = new Socket("127.0.0.1", 5555);
   ;
   bw = new BufferedWriter(new FileWriter("E:\\test2.txt"));
   is = s.getInputStream();
   len = is.read(buf);
   bw.write(new String(buf, 0, len));
   System.out.println(new String(buf, 0, len));
   bw.flush();
  } catch (Exception ex) {
   ex.printStackTrace();
  } finally {
   try {
    is.close();
    s.close();
    bw.close();
   } catch (IOException e) {
    System.out.println(e.getMessage());
   }
  }
 }
}

/* ESP HTTP Client Example This example code is in the Public Domain (or CC0 licensed, at your option.) Unless required by applicable law or agreed to in writing, this software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ #include <string.h> #include <sys/param.h> #include <stdlib.h> #include <ctype.h> #include "esp_log.h" #include "nvs_flash.h" #include "esp_event.h" #include "esp_netif.h" #include "protocol_examples_common.h" #include "protocol_examples_utils.h" #include "esp_tls.h" #if CONFIG_MBEDTLS_CERTIFICATE_BUNDLE #include "esp_crt_bundle.h" #endif #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_system.h" #include "esp_http_client.h" #define MAX_HTTP_RECV_BUFFER 512 #define MAX_HTTP_OUTPUT_BUFFER 2048 static const char *TAG = "HTTP_CLIENT"; /* Root cert for howsmyssl.com, taken from howsmyssl_com_root_cert.pem The PEM file was extracted from the output of this command: openssl s_client -showcerts -connect www.howsmyssl.com:443 </dev/null The CA root cert is the last cert given in the chain of certs. To embed it in the app binary, the PEM file is named in the component.mk COMPONENT_EMBED_TXTFILES variable. */ extern const char howsmyssl_com_root_cert_pem_start[] asm("_binary_howsmyssl_com_root_cert_pem_start"); extern const char howsmyssl_com_root_cert_pem_end[] asm("_binary_howsmyssl_com_root_cert_pem_end"); esp_err_t _http_event_handler(esp_http_client_event_t *evt) { static char *output_buffer; // Buffer to store response of http request from event handler static int output_len; // Stores number of bytes read switch(evt->event_id) { case HTTP_EVENT_ERROR: ESP_LOGD(TAG, "HTTP_EVENT_ERROR"); break; case HTTP_EVENT_ON_CONNECTED: ESP_LOGD(TAG, "HTTP_EVENT_ON_CONNECTED"); break; case HTTP_EVENT_HEADER_SENT: ESP_LOGD(TAG, "HTTP_EVENT_HEADER_SENT"); break; case HTTP_EVENT_ON_HEADER: ESP_LOGD(TAG, "HTTP_EVENT_ON_HEADER, key=%s, value=%s", evt->header_key, evt->header_value); break; case HTTP_EVENT_ON_DATA: ESP_LOGD(TAG, "HTTP_EVENT_ON_DATA, len=%d", evt->data_len); // Clean the buffer in case of a new request if (output_len == 0 && evt->user_data) { // we are just starting to copy the output data into the use memset(evt->user_data, 0, MAX_HTTP_OUTPUT_BUFFER); } /* * Check for chunked encoding is added as the URL for chunked encoding used in this example returns binary data. * However, event handler can also be used in case chunked encoding is used. */ if (!esp_http_client_is_chunked_response(evt->client)) { // If user_data buffer is configured, copy the response into the buffer int copy_len = 0; if (evt->user_data) { // The last byte in evt->user_data is kept for the NULL character in case of out-of-bound access. copy_len = MIN(evt->data_len, (MAX_HTTP_OUTPUT_BUFFER - output_len)); if (copy_len) { memcpy(evt->user_data + output_len, evt->data, copy_len); } } else { int content_len = esp_http_client_get_content_length(evt->client); if (output_buffer == NULL) { // We initialize output_buffer with 0 because it is used by strlen() and similar functions therefore should be null terminated. output_buffer = (char *) calloc(content_len + 1, sizeof(char)); output_len = 0; if (output_buffer == NULL) { ESP_LOGE(TAG, "Failed to allocate memory for output buffer"); return ESP_FAIL; } } copy_len = MIN(evt->data_len, (content_len - output_len)); if (copy_len) { memcpy(output_buffer + output_len, evt->data, copy_len); } } output_len += copy_len; } break; case HTTP_EVENT_ON_FINISH: ESP_LOGD(TAG, "HTTP_EVENT_ON_FINISH"); if (output_buffer != NULL) { #if CONFIG_EXAMPLE_ENABLE_RESPONSE_BUFFER_DUMP ESP_LOG_BUFFER_HEX(TAG, output_buffer, output_len); #endif free(output_buffer); output_buffer = NULL; } output_len = 0; break; case HTTP_EVENT_DISCONNECTED: ESP_LOGI(TAG, "HTTP_EVENT_DISCONNECTED"); int mbedtls_err = 0; esp_err_t err = esp_tls_get_and_clear_last_error((esp_tls_error_handle_t)evt->data, &mbedtls_err, NULL); if (err != 0) { ESP_LOGI(TAG, "Last esp error code: 0x%x", err); ESP_LOGI(TAG, "Last mbedtls failure: 0x%x", mbedtls_err); } if (output_buffer != NULL) { free(output_buffer); output_buffer = NULL; } output_len = 0; break; case HTTP_EVENT_REDIRECT: ESP_LOGD(TAG, "HTTP_EVENT_REDIRECT"); esp_http_client_set_header(evt->client, "From", "user@example.com"); esp_http_client_set_header(evt->client, "Accept", "text/html"); esp_http_client_set_redirection(evt->client); break; } return ESP_OK; } static void http_rest_with_url(void) { // Declare local_response_buffer with size (MAX_HTTP_OUTPUT_BUFFER + 1) to prevent out of bound access when // it is used by functions like strlen(). The buffer should only be used upto size MAX_HTTP_OUTPUT_BUFFER char local_response_buffer[MAX_HTTP_OUTPUT_BUFFER + 1] = {0}; /** * NOTE: All the configuration parameters for http_client must be specified 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 = CONFIG_EXAMPLE_HTTP_ENDPOINT, .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_LOGI(TAG, "HTTP request with url =>"); 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 = %"PRId64, 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)); // POST const char *post_data = "{\"field1\":\"value1\"}"; esp_http_client_set_url(client, "http://"CONFIG_EXAMPLE_HTTP_ENDPOINT"/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) { ESP_LOGI(TAG, "HTTP POST Status = %d, content_length = %"PRId64, esp_http_client_get_status_code(client), esp_http_client_get_content_length(client)); } else { ESP_LOGE(TAG, "HTTP POST request failed: %s", esp_err_to_name(err)); } //PUT esp_http_client_set_url(client, "http://"CONFIG_EXAMPLE_HTTP_ENDPOINT"/put"); esp_http_client_set_method(client, HTTP_METHOD_PUT); err = esp_http_client_perform(client); if (err == ESP_OK) { ESP_LOGI(TAG, "HTTP PUT Status = %d, content_length = %"PRId64, esp_http_client_get_status_code(client), esp_http_client_get_content_length(client)); } else { ESP_LOGE(TAG, "HTTP PUT request failed: %s", esp_err_to_name(err)); } //PATCH esp_http_client_set_url(client, "http://"CONFIG_EXAMPLE_HTTP_ENDPOINT"/patch"); esp_http_client_set_method(client, HTTP_METHOD_PATCH); esp_http_client_set_post_field(client, NULL, 0); err = esp_http_client_perform(client); if (err == ESP_OK) { ESP_LOGI(TAG, "HTTP PATCH Status = %d, content_length = %"PRId64, esp_http_client_get_status_code(client), esp_http_client_get_content_length(client)); } else { ESP_LOGE(TAG, "HTTP PATCH request failed: %s", esp_err_to_name(err)); } //DELETE esp_http_client_set_url(client, "http://"CONFIG_EXAMPLE_HTTP_ENDPOINT"/delete"); esp_http_client_set_method(client, HTTP_METHOD_DELETE); err = esp_http_client_perform(client); if (err == ESP_OK) { ESP_LOGI(TAG, "HTTP DELETE Status = %d, content_length = %"PRId64, esp_http_client_get_status_code(client), esp_http_client_get_content_length(client)); } else { ESP_LOGE(TAG, "HTTP DELETE request failed: %s", esp_err_to_name(err)); } //HEAD esp_http_client_set_url(client, "http://"CONFIG_EXAMPLE_HTTP_ENDPOINT"/get"); esp_http_client_set_method(client, HTTP_METHOD_HEAD); err = esp_http_client_perform(client); if (err == ESP_OK) { ESP_LOGI(TAG, "HTTP HEAD Status = %d, content_length = %"PRId64, esp_http_client_get_status_code(client), esp_http_client_get_content_length(client)); } else { ESP_LOGE(TAG, "HTTP HEAD request failed: %s", esp_err_to_name(err)); } esp_http_client_cleanup(client); } static void http_rest_with_hostname_path(void) { esp_http_client_config_t config = { .host = CONFIG_EXAMPLE_HTTP_ENDPOINT, .path = "/get", .transport_type = HTTP_TRANSPORT_OVER_TCP, .event_handler = _http_event_handler, }; ESP_LOGI(TAG, "HTTP request with hostname and path =>"); 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 = %"PRId64, 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)); } // POST const char *post_data = "field1=value1&field2=value2"; esp_http_client_set_url(client, "/post"); esp_http_client_set_method(client, HTTP_METHOD_POST); esp_http_client_set_post_field(client, post_data, strlen(post_data)); err = esp_http_client_perform(client); if (err == ESP_OK) { ESP_LOGI(TAG, "HTTP POST Status = %d, content_length = %"PRId64, esp_http_client_get_status_code(client), esp_http_client_get_content_length(client)); } else { ESP_LOGE(TAG, "HTTP POST request failed: %s", esp_err_to_name(err)); } //PUT esp_http_client_set_url(client, "/put"); esp_http_client_set_method(client, HTTP_METHOD_PUT); err = esp_http_client_perform(client); if (err == ESP_OK) { ESP_LOGI(TAG, "HTTP PUT Status = %d, content_length = %"PRId64, esp_http_client_get_status_code(client), esp_http_client_get_content_length(client)); } else { ESP_LOGE(TAG, "HTTP PUT request failed: %s", esp_err_to_name(err)); } //PATCH esp_http_client_set_url(client, "/patch"); esp_http_client_set_method(client, HTTP_METHOD_PATCH); esp_http_client_set_post_field(client, NULL, 0); err = esp_http_client_perform(client); if (err == ESP_OK) { ESP_LOGI(TAG, "HTTP PATCH Status = %d, content_length = %"PRId64, esp_http_client_get_status_code(client), esp_http_client_get_content_length(client)); } else { ESP_LOGE(TAG, "HTTP PATCH request failed: %s", esp_err_to_name(err)); } //DELETE esp_http_client_set_url(client, "/delete"); esp_http_client_set_method(client, HTTP_METHOD_DELETE); err = esp_http_client_perform(client); if (err == ESP_OK) { ESP_LOGI(TAG, "HTTP DELETE Status = %d, content_length = %"PRId64, esp_http_client_get_status_code(client), esp_http_client_get_content_length(client)); } else { ESP_LOGE(TAG, "HTTP DELETE request failed: %s", esp_err_to_name(err)); } //HEAD esp_http_client_set_url(client, "/get"); esp_http_client_set_method(client, HTTP_METHOD_HEAD); err = esp_http_client_perform(client); if (err == ESP_OK) { ESP_LOGI(TAG, "HTTP HEAD Status = %d, content_length = %"PRId64, esp_http_client_get_status_code(client), esp_http_client_get_content_length(client)); } else { ESP_LOGE(TAG, "HTTP HEAD request failed: %s", esp_err_to_name(err)); } esp_http_client_cleanup(client); } #if CONFIG_ESP_HTTP_CLIENT_ENABLE_BASIC_AUTH static void http_auth_basic(void) { /** * Note: `max_authorization_retries` in esp_http_client_config_t * can be used to configure number of retry attempts to be performed * in case unauthorized status code is received. * * To disable authorization retries, set max_authorization_retries to -1. */ esp_http_client_config_t config = { .url = "http://user:passwd@"CONFIG_EXAMPLE_HTTP_ENDPOINT"/basic-auth/user/passwd", .event_handler = _http_event_handler, .auth_type = HTTP_AUTH_TYPE_BASIC, .max_authorization_retries = -1, }; ESP_LOGI(TAG, "HTTP Basic Auth request =>"); esp_http_client_handle_t client = esp_http_client_init(&config); esp_err_t err = esp_http_client_perform(client); if (err == ESP_OK) { ESP_LOGI(TAG, "HTTP Basic Auth Status = %d, content_length = %"PRId64, esp_http_client_get_status_code(client), esp_http_client_get_content_length(client)); } else { ESP_LOGE(TAG, "Error perform http request %s", esp_err_to_name(err)); } esp_http_client_cleanup(client); } static void http_auth_basic_redirect(void) { esp_http_client_config_t config = { .url = "http://user:passwd@"CONFIG_EXAMPLE_HTTP_ENDPOINT"/basic-auth/user/passwd", .event_handler = _http_event_handler, }; ESP_LOGI(TAG, "HTTP Basic Auth redirect request =>"); esp_http_client_handle_t client = esp_http_client_init(&config); esp_err_t err = esp_http_client_perform(client); if (err == ESP_OK) { ESP_LOGI(TAG, "HTTP Basic Auth redirect Status = %d, content_length = %"PRId64, esp_http_client_get_status_code(client), esp_http_client_get_content_length(client)); } else { ESP_LOGE(TAG, "Error perform http request %s", esp_err_to_name(err)); } esp_http_client_cleanup(client); } #endif #if CONFIG_ESP_HTTP_CLIENT_ENABLE_DIGEST_AUTH static void http_auth_digest_md5(void) { esp_http_client_config_t config = { .url = "http://user:passwd@"CONFIG_EXAMPLE_HTTP_ENDPOINT"/digest-auth/auth/user/passwd/MD5/never", .event_handler = _http_event_handler, }; ESP_LOGI(TAG, "HTTP MD5 Digest Auth request =>"); esp_http_client_handle_t client = esp_http_client_init(&config); esp_err_t err = esp_http_client_perform(client); if (err == ESP_OK) { ESP_LOGI(TAG, "HTTP MD5 Digest Auth Status = %d, content_length = %"PRId64, esp_http_client_get_status_code(client), esp_http_client_get_content_length(client)); } else { ESP_LOGE(TAG, "Error performing http request %s", esp_err_to_name(err)); } esp_http_client_cleanup(client); } static void http_auth_digest_sha256(void) { esp_http_client_config_t config = { .url = "http://user:passwd@"CONFIG_EXAMPLE_HTTP_ENDPOINT"/digest-auth/auth/user/passwd/SHA-256/never", .event_handler = _http_event_handler, .buffer_size_tx = 1024, // Increase buffer size as header size will increase as it contains SHA-256. }; ESP_LOGI(TAG, "HTTP SHA256 Digest Auth request =>"); esp_http_client_handle_t client = esp_http_client_init(&config); esp_err_t err = esp_http_client_perform(client); if (err == ESP_OK) { ESP_LOGI(TAG, "HTTP SHA256 Digest Auth Status = %d, content_length = %"PRId64, esp_http_client_get_status_code(client), esp_http_client_get_content_length(client)); } else { ESP_LOGE(TAG, "Error performing http request %s", esp_err_to_name(err)); } esp_http_client_cleanup(client); } #endif #if CONFIG_MBEDTLS_CERTIFICATE_BUNDLE static void https_with_url(void) { esp_http_client_config_t config = { .url = "https://www.howsmyssl.com", .event_handler = _http_event_handler, .crt_bundle_attach = esp_crt_bundle_attach, }; ESP_LOGI(TAG, "HTTPS request with url =>"); esp_http_client_handle_t client = esp_http_client_init(&config); esp_err_t err = esp_http_client_perform(client); if (err == ESP_OK) { ESP_LOGI(TAG, "HTTPS Status = %d, content_length = %"PRId64, esp_http_client_get_status_code(client), esp_http_client_get_content_length(client)); } else { ESP_LOGE(TAG, "Error perform http request %s", esp_err_to_name(err)); } esp_http_client_cleanup(client); } #endif // CONFIG_MBEDTLS_CERTIFICATE_BUNDLE static void https_with_hostname_path(void) { esp_http_client_config_t config = { .host = "www.howsmyssl.com", .path = "/", .transport_type = HTTP_TRANSPORT_OVER_SSL, .event_handler = _http_event_handler, .cert_pem = howsmyssl_com_root_cert_pem_start, }; ESP_LOGI(TAG, "HTTPS request with hostname and path =>"); esp_http_client_handle_t client = esp_http_client_init(&config); esp_err_t err = esp_http_client_perform(client); if (err == ESP_OK) { ESP_LOGI(TAG, "HTTPS Status = %d, content_length = %"PRId64, esp_http_client_get_status_code(client), esp_http_client_get_content_length(client)); } else { ESP_LOGE(TAG, "Error perform http request %s", esp_err_to_name(err)); } esp_http_client_cleanup(client); } static void http_encoded_query(void) { esp_http_client_config_t config = { .host = CONFIG_EXAMPLE_HTTP_ENDPOINT, .path = "/get", .event_handler = _http_event_handler, }; ESP_LOGI(TAG, "HTTP GET request with encoded query =>"); static const char query_val[] = "ABC xyz!012@#%&"; char query_val_enc[64] = {0}; uint32_t enc_len = example_uri_encode(query_val_enc, query_val, strlen(query_val)); if (enc_len > 0) { ESP_LOG_BUFFER_HEXDUMP(TAG, query_val_enc, enc_len, ESP_LOG_DEBUG); config.query = query_val_enc; } esp_http_client_handle_t client = esp_http_client_init(&config); esp_err_t err = esp_http_client_perform(client); if (err == ESP_OK) { ESP_LOGI(TAG, "HTTP GET Status = %d, content_length = %"PRId64, 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)); } } static void http_relative_redirect(void) { esp_http_client_config_t config = { .url = "http://"CONFIG_EXAMPLE_HTTP_ENDPOINT"/relative-redirect/3", .event_handler = _http_event_handler, }; ESP_LOGI(TAG, "HTTP Relative path redirect request =>"); esp_http_client_handle_t client = esp_http_client_init(&config); esp_err_t err = esp_http_client_perform(client); if (err == ESP_OK) { ESP_LOGI(TAG, "HTTP Relative path redirect Status = %d, content_length = %"PRId64, esp_http_client_get_status_code(client), esp_http_client_get_content_length(client)); } else { ESP_LOGE(TAG, "Error perform http request %s", esp_err_to_name(err)); } esp_http_client_cleanup(client); } static void http_absolute_redirect(void) { esp_http_client_config_t config = { .url = "http://"CONFIG_EXAMPLE_HTTP_ENDPOINT"/absolute-redirect/3", .event_handler = _http_event_handler, }; ESP_LOGI(TAG, "HTTP Absolute path redirect request =>"); esp_http_client_handle_t client = esp_http_client_init(&config); esp_err_t err = esp_http_client_perform(client); if (err == ESP_OK) { ESP_LOGI(TAG, "HTTP Absolute path redirect Status = %d, content_length = %"PRId64, esp_http_client_get_status_code(client), esp_http_client_get_content_length(client)); } else { ESP_LOGE(TAG, "Error perform http request %s", esp_err_to_name(err)); } esp_http_client_cleanup(client); } static void http_absolute_redirect_manual(void) { esp_http_client_config_t config = { .url = "http://"CONFIG_EXAMPLE_HTTP_ENDPOINT"/absolute-redirect/3", .event_handler = _http_event_handler, .disable_auto_redirect = true, }; ESP_LOGI(TAG, "HTTP Absolute path redirect (manual) request =>"); esp_http_client_handle_t client = esp_http_client_init(&config); esp_err_t err = esp_http_client_perform(client); if (err == ESP_OK) { ESP_LOGI(TAG, "HTTP Absolute path redirect (manual) Status = %d, content_length = %"PRId64, esp_http_client_get_status_code(client), esp_http_client_get_content_length(client)); } else { ESP_LOGE(TAG, "Error perform http request %s", esp_err_to_name(err)); } esp_http_client_cleanup(client); } static void http_redirect_to_https(void) { esp_http_client_config_t config = { .url = "http://"CONFIG_EXAMPLE_HTTP_ENDPOINT"/redirect-to?url=https://www.howsmyssl.com", .event_handler = _http_event_handler, .cert_pem = howsmyssl_com_root_cert_pem_start, }; ESP_LOGI(TAG, "HTTP redirect to HTTPS request =>"); esp_http_client_handle_t client = esp_http_client_init(&config); esp_err_t err = esp_http_client_perform(client); if (err == ESP_OK) { ESP_LOGI(TAG, "HTTP redirect to HTTPS Status = %d, content_length = %"PRId64, esp_http_client_get_status_code(client), esp_http_client_get_content_length(client)); } else { ESP_LOGE(TAG, "Error perform http request %s", esp_err_to_name(err)); } esp_http_client_cleanup(client); } static void http_download_chunk(void) { esp_http_client_config_t config = { .url = "http://"CONFIG_EXAMPLE_HTTP_ENDPOINT"/stream-bytes/8912", .event_handler = _http_event_handler, }; ESP_LOGI(TAG, "HTTP chunk encoding request =>"); esp_http_client_handle_t client = esp_http_client_init(&config); esp_err_t err = esp_http_client_perform(client); if (err == ESP_OK) { ESP_LOGI(TAG, "HTTP chunk encoding Status = %d, content_length = %"PRId64, esp_http_client_get_status_code(client), esp_http_client_get_content_length(client)); } else { ESP_LOGE(TAG, "Error perform http request %s", esp_err_to_name(err)); } esp_http_client_cleanup(client); } static void http_perform_as_stream_reader(void) { char *buffer = malloc(MAX_HTTP_RECV_BUFFER + 1); if (buffer == NULL) { ESP_LOGE(TAG, "Cannot malloc http receive buffer"); return; } esp_http_client_config_t config = { .url = "http://"CONFIG_EXAMPLE_HTTP_ENDPOINT"/get", }; ESP_LOGI(TAG, "HTTP Stream reader request =>"); esp_http_client_handle_t client = esp_http_client_init(&config); esp_err_t err; 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_LOGD(TAG, "read_len = %d", read_len); } ESP_LOGI(TAG, "HTTP Stream reader Status = %d, content_length = %"PRId64, esp_http_client_get_status_code(client), esp_http_client_get_content_length(client)); esp_http_client_close(client); esp_http_client_cleanup(client); free(buffer); } static void https_async(void) { esp_http_client_config_t config = { .url = "https://postman-echo.com/post", .event_handler = _http_event_handler, .crt_bundle_attach = esp_crt_bundle_attach, .is_async = true, .timeout_ms = 5000, }; ESP_LOGI(TAG, "HTTPS async requests =>"); esp_http_client_handle_t client = esp_http_client_init(&config); esp_err_t err; const char *post_data = "Using a Palantír requires a person with great strength of will and wisdom. The Palantíri were meant to " "be used by the Dúnedain to communicate throughout the Realms in Exile. During the War of the Ring, " "the Palantíri were used by many individuals. Sauron used the Ithil-stone to take advantage of the users " "of the other two stones, the Orthanc-stone and Anor-stone, but was also susceptible to deception himself."; esp_http_client_set_method(client, HTTP_METHOD_POST); esp_http_client_set_post_field(client, post_data, strlen(post_data)); while (1) { err = esp_http_client_perform(client); if (err != ESP_ERR_HTTP_EAGAIN) { break; } } if (err == ESP_OK) { ESP_LOGI(TAG, "HTTPS Status = %d, content_length = %"PRId64, esp_http_client_get_status_code(client), esp_http_client_get_content_length(client)); } else { ESP_LOGE(TAG, "Error perform http request %s", esp_err_to_name(err)); } esp_http_client_cleanup(client); // Test HTTP_METHOD_HEAD with is_async enabled config.url = "https://"CONFIG_EXAMPLE_HTTP_ENDPOINT"/get"; config.event_handler = _http_event_handler; config.crt_bundle_attach = esp_crt_bundle_attach; config.is_async = true; config.timeout_ms = 5000; client = esp_http_client_init(&config); esp_http_client_set_method(client, HTTP_METHOD_HEAD); while (1) { err = esp_http_client_perform(client); if (err != ESP_ERR_HTTP_EAGAIN) { break; } } if (err == ESP_OK) { ESP_LOGI(TAG, "HTTPS Status = %d, content_length = %"PRId64, esp_http_client_get_status_code(client), esp_http_client_get_content_length(client)); } else { ESP_LOGE(TAG, "Error perform http request %s", esp_err_to_name(err)); } esp_http_client_cleanup(client); } static void https_with_invalid_url(void) { esp_http_client_config_t config = { .url = "https://not.existent.url", .event_handler = _http_event_handler, }; ESP_LOGI(TAG, "HTTPS request with invalid url =>"); esp_http_client_handle_t client = esp_http_client_init(&config); esp_err_t err = esp_http_client_perform(client); if (err == ESP_OK) { ESP_LOGI(TAG, "HTTPS Status = %d, content_length = %"PRId64, esp_http_client_get_status_code(client), esp_http_client_get_content_length(client)); } else { ESP_LOGE(TAG, "Error perform http request %s", esp_err_to_name(err)); } esp_http_client_cleanup(client); } /* * http_native_request() demonstrates use of low level APIs to connect to a server, * make a http request and read response. Event handler is not used in this case. * Note: This approach should only be used in case use of low level APIs is required. * The easiest way is to use esp_http_perform() */ static void http_native_request(void) { // Declare local_response_buffer with size (MAX_HTTP_OUTPUT_BUFFER + 1) to prevent out of bound access when // it is used by functions like strlen(). The buffer should only be used upto size MAX_HTTP_OUTPUT_BUFFER char output_buffer[MAX_HTTP_OUTPUT_BUFFER + 1] = {0}; // Buffer to store response of http request int content_length = 0; esp_http_client_config_t config = { .url = "http://"CONFIG_EXAMPLE_HTTP_ENDPOINT"/get", }; ESP_LOGI(TAG, "HTTP native request =>"); esp_http_client_handle_t client = esp_http_client_init(&config); // GET Request esp_http_client_set_method(client, HTTP_METHOD_GET); esp_err_t err = esp_http_client_open(client, 0); if (err != ESP_OK) { ESP_LOGE(TAG, "Failed to open HTTP connection: %s", esp_err_to_name(err)); } else { content_length = esp_http_client_fetch_headers(client); if (content_length < 0) { ESP_LOGE(TAG, "HTTP client fetch headers failed"); } else { int data_read = esp_http_client_read_response(client, output_buffer, MAX_HTTP_OUTPUT_BUFFER); if (data_read >= 0) { ESP_LOGI(TAG, "HTTP GET Status = %d, content_length = %"PRId64, esp_http_client_get_status_code(client), esp_http_client_get_content_length(client)); ESP_LOG_BUFFER_HEX(TAG, output_buffer, data_read); } else { ESP_LOGE(TAG, "Failed to read response"); } } } esp_http_client_close(client); // POST Request const char *post_data = "{\"field1\":\"value1\"}"; esp_http_client_set_url(client, "http://"CONFIG_EXAMPLE_HTTP_ENDPOINT"/post"); esp_http_client_set_method(client, HTTP_METHOD_POST); esp_http_client_set_header(client, "Content-Type", "application/json"); err = esp_http_client_open(client, strlen(post_data)); if (err != ESP_OK) { ESP_LOGE(TAG, "Failed to open HTTP connection: %s", esp_err_to_name(err)); } else { int wlen = esp_http_client_write(client, post_data, strlen(post_data)); if (wlen < 0) { ESP_LOGE(TAG, "Write failed"); } content_length = esp_http_client_fetch_headers(client); if (content_length < 0) { ESP_LOGE(TAG, "HTTP client fetch headers failed"); } else { int data_read = esp_http_client_read_response(client, output_buffer, MAX_HTTP_OUTPUT_BUFFER); if (data_read >= 0) { ESP_LOGI(TAG, "HTTP POST Status = %d, content_length = %"PRId64, esp_http_client_get_status_code(client), esp_http_client_get_content_length(client)); ESP_LOG_BUFFER_HEX(TAG, output_buffer, strlen(output_buffer)); } else { ESP_LOGE(TAG, "Failed to read response"); } } } esp_http_client_cleanup(client); } #if CONFIG_MBEDTLS_CERTIFICATE_BUNDLE static void http_partial_download(void) { esp_http_client_config_t config = { .url = "https://dl.espressif.com/dl/esp-idf/ci/esp_http_client_demo.txt", .event_handler = _http_event_handler, .crt_bundle_attach = esp_crt_bundle_attach, }; ESP_LOGI(TAG, "HTTP partial download =>"); esp_http_client_handle_t client = esp_http_client_init(&config); // Download a file excluding first 10 bytes esp_http_client_set_header(client, "Range", "bytes=10-"); esp_err_t err = esp_http_client_perform(client); if (err == ESP_OK) { ESP_LOGI(TAG, "HTTP Status = %d, content_length = %"PRId64, esp_http_client_get_status_code(client), esp_http_client_get_content_length(client)); } else { ESP_LOGE(TAG, "HTTP request failed: %s", esp_err_to_name(err)); } // Download last 10 bytes of a file esp_http_client_set_header(client, "Range", "bytes=-10"); err = esp_http_client_perform(client); if (err == ESP_OK) { ESP_LOGI(TAG, "HTTP Status = %d, content_length = %"PRId64, esp_http_client_get_status_code(client), esp_http_client_get_content_length(client)); } else { ESP_LOGE(TAG, "HTTP request failed: %s", esp_err_to_name(err)); } // Download 10 bytes from 11 to 20 esp_http_client_set_header(client, "Range", "bytes=11-20"); err = esp_http_client_perform(client); if (err == ESP_OK) { ESP_LOGI(TAG, "HTTP Status = %d, content_length = %"PRId64, esp_http_client_get_status_code(client), esp_http_client_get_content_length(client)); } else { ESP_LOGE(TAG, "HTTP request failed: %s", esp_err_to_name(err)); } esp_http_client_cleanup(client); } #endif // CONFIG_MBEDTLS_CERTIFICATE_BUNDLE static void http_test_task(void *pvParameters) { http_rest_with_url(); http_rest_with_hostname_path(); #if CONFIG_ESP_HTTP_CLIENT_ENABLE_BASIC_AUTH http_auth_basic(); http_auth_basic_redirect(); #endif #if CONFIG_ESP_HTTP_CLIENT_ENABLE_DIGEST_AUTH http_auth_digest_md5(); http_auth_digest_sha256(); #endif http_encoded_query(); http_relative_redirect(); http_absolute_redirect(); http_absolute_redirect_manual(); #if CONFIG_MBEDTLS_CERTIFICATE_BUNDLE https_with_url(); #endif https_with_hostname_path(); http_redirect_to_https(); http_download_chunk(); http_perform_as_stream_reader(); https_async(); https_with_invalid_url(); http_native_request(); #if CONFIG_MBEDTLS_CERTIFICATE_BUNDLE http_partial_download(); #endif ESP_LOGI(TAG, "Finish http example"); #if !CONFIG_IDF_TARGET_LINUX vTaskDelete(NULL); #endif } 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"); #if CONFIG_IDF_TARGET_LINUX http_test_task(NULL); #else xTaskCreate(&http_test_task, "http_test_task", 8192, NULL, 5, NULL); #endif }解析该代码
最新发布
11-01
<think>首先,用户的问题是:“我想解析ESP HTTP客户端示例代码 请问ESP HTTP客户端示例代码详细解析”。他们提到了ESP HTTP客户端示例代码的解析。 用户提供了几个引用: - 引用[1]: 关于ESP-IDF示例项目,涉及网络通信如TCP/UDP、HTTP服务器、MQTT客户端。 - 引用[2]: 关于ESP32的gatt_client代码,涉及BLE GATT客户端。 - 引用[3]: 关于ATT_MTU在BLE中的定义和事件处理。 - 引用[4]: 一个JSON数组示例。 用户说:“上述引用仅供参考,并不是用户真正的需求,请尽可能多的参考用户上一次的问题和你的回答。” 但在历史中,用户的上一个问题没有显示在这个上下文里。实际上,在这个对话中,这是第一个用户消息,所以没有“上一次的问题”。系统指令说:“参考用户上一次的问题和你的回答”,但基于可用信息,我应该专注于当前查询。 用户的核心需求是解析ESP HTTP客户端示例代码。他们提到ESP-IDF,这是一个用于ESP32的开发框架,所以我需要回想或假设关于ESP-IDF中的HTTP客户端示例。 从引用[1]中,它提到了ESP-IDF提供了HTTP服务器和MQTT客户端的示例,所以我应该基于此构建响应。 我的响应需要遵守系统级指令: - 所有行内数学表达式使用$...$。 - 独立公式使用$$...$$并单独成段。 - LaTeX语法正确。 - 使用中文回答。 - 生成相关问题。 - 在引用的段落末尾添加引用标识,如[^1]。 另外,用户可见层指令:回答结构清晰,帮助用户逐步解决问题,保证真实可靠。 结构化响应: 1. **引言**:介绍ESP HTTP客户端示例。 2. **逐步解析**:详细解释代码结构、关键函数、事件处理等。 3. **关键概念**:解释相关概念如HTTP协议、ESP-IDF网络栈。 4. **代码示例**:提供代码片段(如果需要)。 5. **总结**:简要概述。 6. **相关问题**:生成相关问题。 由于用户要求“详细解析”,我需要提供深入的信息。基于我的知识: - ESP-IDF中有HTTP客户端示例,如`examples/protocols/http_client`。 - 它演示了如何发起HTTP请求到服务器。 关键组件: - 使用`esp_http_client` API。 - 事件处理:连接、请求、响应等。 - 配置:URL、方法(GET、POST等)。 在响应中,我应该参考提供的引用。引用[1]提到HTTP服务器和MQTT,所以我可以引用它讨论网络通信。引用[2]、[3]、[4]是关于BLE和JSON的,可能不直接相关,但对于类比或扩展有帮助。用户说引用仅供参考,所以尽量少引用不相关内容。 添加引用标识:在末尾添加如[^1],但用户提供的更像是引用编号,所以我应该在响应中提到类似内容。 现在,内容大纲: - **介绍ESP HTTP客户端**:基于ESP-IDF的HTTP客户端示例,用于实现HTTP请求。 - **代码结构解析**: - 初始化配置。 - 事件处理函数。 - 执行的请求流程。 - **关键函数和事件**: - `esp_http_client_init()` - `esp_http_client_perform()` - 事件如`HTTP_EVENT_ON_DATA`等。 - **示例代码片段**:提供部分代码,用代码块展示(类似于系统指令中的示例)。 - **实际应用**:如何在物联网中使用。 - **总结**:回顾重点。 - **相关问题**:生成3-4个相关问题。 确保使用中文。 生成相关问题: 1. 如何配置ESP HTTP客户端发送POST请求? 2. ESP HTTP客户端如何处理HTTPS连接? 3. 如何优化ESP HTTP客户端的性能? 4. ESP HTTP客户端有哪些常见错误及其解决方法? 添加引用:在提到通用网络通信时,引用[1];其他引用可能不直接适用。 </think>### ESP HTTP客户端示例代码详细解析 ESP-IDF(Espressif IoT Development Framework)是专为ESP32芯片设计的开发框架,提供了丰富的网络通信示例。其中,HTTP客户端示例展示了如何使用ESP32实现HTTP协议通信,包括发起GET、POST请求等。以下我将基于ESP-IDF的标准示例(如`examples/protocols/http_client`)逐步解析关键部分,确保内容真实可靠,并参考ESP-IDF官方文档[^1]。解析分为代码结构、关键函数、事件处理和实际应用四个部分。 #### 1. **代码结构与初始化** ESP HTTP客户端示例的核心是使用`esp_http_client`组件,它抽象了底层网络栈(如TCP/IP),简化HTTP通信。代码通常包含以下步骤: - **配置初始化**:通过`esp_http_client_config_t`结构配置URL、请求方法、超时等参数。例如: ```c #include "esp_http_client.h" void app_main() { esp_http_client_config_t config = { .url = "http://example.com/api", // 目标HTTP服务器URL .method = HTTP_METHOD_GET, // 请求方法,如GET或POST .timeout_ms = 5000, // 超时时间 }; esp_http_client_handle_t client = esp_http_client_init(&config); // 初始化客户端 esp_err_t err = esp_http_client_perform(client); // 执行请求 esp_http_client_cleanup(client); // 清理资源 } ``` 在此: - `.url`指定服务器地址;可通过参数设置HTTPS(需证书)。 - `.method`定义HTTP方法;常见还有`HTTP_METHOD_POST`。 - `esp_http_client_init()`初始化句柄,`esp_http_client_perform()`执行请求,并返回错误码(如`ESP_OK`表示成功)。 - **事件处理**:客户端通过事件驱动模型处理响应,需要注册事件回调函数。初始化时可选配事件处理函数[^1]。 #### 2. **关键函数与事件解析** 示例的核心是事件处理函数,理解事件流是解析的重点。当调用`esp_http_client_perform()`时,会触发一系列事件: - **事件类型**:常用事件包括: - `HTTP_EVENT_ON_CONNECTED`:连接服务器成功时触发。 - `HTTP_EVENT_HEADERS_SENT`:请求头发送完毕。 - `HTTP_EVENT_ON_HEADER`:接收到服务器响应头时触发。 - `HTTP_EVENT_ON_DATA`:接收到响应数据时触发;需在此处理数据块(如解析JSON)。 - `HTTP_EVENT_ON_FINISH`:请求完成时触发。 - `HTTP_EVENT_DISCONNECTED`:连接断开时触发;用于错误处理。 事件结构在`esp_http_client_event_t`中定义,包含数据指针、长度等信息。 - **回调函数实现**:示例代码通常定义一个静态函数处理事件: ```c static esp_err_t http_event_handler(esp_http_client_event_t *evt) { switch (evt->event_id) { case HTTP_EVENT_ON_DATA: // 处理接收的数据,evt->data指向数据缓冲区 printf("Received data: %.*s\n", evt->data_len, (char*)evt->data); break; case HTTP_EVENT_ON_FINISH: printf("Request completed\n"); break; case HTTP_EVENT_ERROR: printf("HTTP error occurred\n"); break; default: break; } return ESP_OK; } ``` 在配置中绑定此回调: ```c esp_http_client_config_t config = { .url = "http://example.com", .event_handler = http_event_handler, // 注册事件处理 }; ``` 解析要点: - `HTTP_EVENT_ON_DATA`事件可能多次触发(分块传输),需累积或直接处理数据。 - 错误处理:通过`HTTP_EVENT_ERROR`或返回值检查错误(如网络故障);使用`esp_http_client_get_status_code()`获取HTTP状态码(如200、404)。 #### 3. **请求执行与数据处理** `esp_http_client_perform()`函数执行全程请求,内部处理TCP连接、数据发送/接收和事件触发流程: - **发送请求**:对于POST请求,需额外设置请求体: ```c esp_http_client_set_post_field(client, "{\"key\":\"value\"}", 15); // 设置JSON请求体 ``` 此处引用[^4]展示了JSON结构示例,可用于数据格式化。 - **接收响应**:在`HTTP_EVENT_ON_DATA`事件中处理数据。例如,解析JSON响应: ```c case HTTP_EVENT_ON_DATA: if (evt->data_len > 0) { // 假设响应为JSON,使用cJSON库解析 cJSON *root = cJSON_Parse((char*)evt->data); if (root != NULL) { cJSON *item = cJSON_GetObjectItem(root, "name"); if (item != NULL) { printf("Name: %s\n", item->valuestring); } cJSON_Delete(root); // 清理内存 } } break; ``` 关键点: - 数据安全:确保缓冲区不溢出;ESP-IDF使用动态内存管理。 - 性能:事件驱动减少阻塞,适合物联网低功耗场景[^1]。 - **资源清理**:请求后必须调用`esp_http_client_cleanup()`释放资源,避免内存泄漏。 #### 4. **实际应用与优化** 此示例广泛应用于物联网设备,如传感器数据上传到云服务器: - **典型场景**:ESP32作为客户端定期发送数据到HTTP服务器(如使用POST上传温度数据)。 - **优化建议**: - 使用HTTPS时,配置证书(`.cert_pem`参数)增强安全。 - 减少内存占用:重用HTTP客户端句柄多次请求。 - 错误恢复:结合Wi-Fi事件处理重连机制。 参考ESP-IDF文档,该示例展示了如何集成到更大项目中,体现了ESP32的网络通信能力[^1]。 #### 总结 ESP HTTP客户端示例通过`esp_http_client`组件实现高效HTTP通信,核心是初始化配置、事件处理和请求执行。代码结构清晰,事件模型确保异步处理,适用于各类物联网应用。在解析时,重点理解事件流和错误处理机制以确保可靠性。更多细节可参考ESP-IDF官方示例代码和文档[^1]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值