1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
| static void http_test_task(void *pvParameters) {
char output_buffer[MAX_HTTP_OUTPUT_BUFFER] = {0}; int content_length = 0;
esp_http_client_config_t config ; memset(&config,0,sizeof(config));
static const char *URL = "http://api.seniverse.com/v3/weather/now.json?key=SCoom38PWDOGScGYt&location=zhengzhou&language=zh-Hans&unit=c"; config.url = URL;
esp_http_client_handle_t client = esp_http_client_init(&config);
esp_http_client_set_method(client, HTTP_METHOD_GET);
while(1) {
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 = %lld", esp_http_client_get_status_code(client), esp_http_client_get_content_length(client)); cJSON* root = NULL; root = cJSON_Parse(output_buffer); if (root == NULL) { ESP_LOGE(TAG, "Error parsing JSON data!"); }
cJSON *results = cJSON_GetObjectItem(root, "results"); if (results == NULL) { ESP_LOGE(TAG, "Failed to get 'results' object!"); cJSON_Delete(root); }
cJSON *location = cJSON_GetObjectItem(results->child, "location"); if (location == NULL) { ESP_LOGE(TAG, "Failed to get 'location' object!"); cJSON_Delete(root); }
cJSON *now = cJSON_GetObjectItem(results->child, "now"); if (now == NULL) { ESP_LOGE(TAG, "Failed to get 'now' object!"); cJSON_Delete(root); }
const char *name = cJSON_GetObjectItem(location, "name")->valuestring; const char *text = cJSON_GetObjectItem(now, "text")->valuestring; const char *temperature = cJSON_GetObjectItem(now, "temperature")->valuestring;
ESP_LOGE(TAG, "Location: %s", name); ESP_LOGE(TAG, "Weather: %s", text); ESP_LOGE(TAG, "Temperature: %s", temperature); } else { ESP_LOGE(TAG, "Failed to read response"); } } }
esp_http_client_close(client);
vTaskDelay(3000/portTICK_PERIOD_MS);
}
}
|