network/http_methods/http_put.c

/*******************************************************************************
* # License
* Copyright 2019 Silicon Laboratories Inc. www.silabs.com
*******************************************************************************
*
* The licensor of this software is Silicon Laboratories Inc. Your use of this
* software is governed by the terms of Silicon Labs Master Software License
* Agreement (MSLA) available at
* www.silabs.com/about-us/legal/master-software-license-agreement. This
* software is distributed to you in Source Code format and is governed by the
* sections of the MSLA applicable to Source Code.
*
******************************************************************************/
#include "common.h"
/*************************************************************************************************/
void http_put_example(void)
{
GOS_LOG("\r\n");
GOS_LOG("Running HTTP: PUT %s", bin_url);
gos_result_t result;
gos_handle_t handle;
const char *content = "{\"messages\":\"Hello from Silabs\"}";
{
.method = GOS_HTTP_PUT,
.url = bin_url,
.content_type = "application/json",
.content_length = strlen(content), // -1 means 'chunked' transfer-encoding
};
GOS_LOG("Issuing http_put request ... ");
if (GOS_FAILED(result, gos_http_open_request(&request, &handle)))
{
GOS_LOG("Request failed: %d", result);
return;
}
GOS_LOG("Adding custom header ... ");
if (GOS_FAILED(result, gos_http_add_header(handle, "x-my-custom-header", "custom_header_data")))
{
GOS_LOG("Failed to add header: %d", result);
return;
}
GOS_LOG("Sending JSON content ... ");
if (GOS_FAILED(result,gos_http_write(handle, content, strlen(content), false)))
{
GOS_LOG("Failed to send HTTP post : %u", result);
}
GOS_LOG("Receiving response ... ");
if (GOS_FAILED(result, gos_http_receive_response(handle, &response)))
{
GOS_LOG("Response failed: %d", result);
return;
}
GOS_LOG("Response code: %d", response.code);
GOS_LOG("Response length: %d", response.content_length);
if (response.content_length > 0)
{
uint32_t bytes_read;
char buffer[256];
GOS_LOG("Response:");
if (GOS_FAILED(result, gos_http_read(handle, buffer, sizeof(buffer)-1, &bytes_read)))
{
GOS_LOG("Failed to read response: %d", result);
return;
}
buffer[bytes_read] = 0;
GOS_LOG("%s", buffer);
}
gos_http_close(handle);
GOS_LOG("Success\r\n");
}