coreHTTP v3.1.1
HTTP/1.1 Client Library
 
Loading...
Searching...
No Matches
core_http_client.h File Reference

User facing functions of the HTTP Client library. More...

#include <stdint.h>
#include <stddef.h>
#include "core_http_config.h"
#include "core_http_config_defaults.h"
#include "transport_interface.h"

Go to the source code of this file.

Data Structures

struct  HTTPRequestHeaders_t
 Represents header data that will be sent in an HTTP request. More...
 
struct  HTTPRequestInfo_t
 Configurations of the initial request headers. More...
 
struct  HTTPClient_ResponseHeaderParsingCallback_t
 Callback to intercept headers during the first parse through of the response as it is received from the network. More...
 
struct  HTTPResponse_t
 Represents an HTTP response. More...
 

Macros

#define HTTP_METHOD_GET   "GET"
 
#define HTTP_METHOD_PUT   "PUT"
 
#define HTTP_METHOD_POST   "POST"
 
#define HTTP_METHOD_HEAD   "HEAD"
 
#define HTTP_MAX_CONTENT_LENGTH_HEADER_LENGTH   sizeof( "Content-Length: 4294967295" ) - 1U
 The maximum Content-Length header field and value that could be written to the request header buffer.
 
#define HTTP_SEND_DISABLE_CONTENT_LENGTH_FLAG   0x1U
 Set this flag to disable automatically writing the Content-Length header to send to the server.
 
#define HTTP_REQUEST_KEEP_ALIVE_FLAG   0x1U
 Set this flag to indicate that the request is for a persistent connection.
 
#define HTTP_REQUEST_NO_USER_AGENT_FLAG   0x2U
 Set this flag to skip the User-Agent in the request headers.
 
#define HTTP_RESPONSE_CONNECTION_CLOSE_FLAG   0x1U
 This will be set to true if header "Connection: close" is found.
 
#define HTTP_RESPONSE_CONNECTION_KEEP_ALIVE_FLAG   0x2U
 This will be set to true if header "Connection: Keep-Alive" is found.
 
#define HTTP_RESPONSE_DO_NOT_PARSE_BODY_FLAG   0x1U
 Set this flag to indicate that the response body should not be parsed.
 
#define HTTP_RANGE_REQUEST_END_OF_FILE   -1
 Flag that represents End of File byte in the range specification of a Range Request. This flag should be used ONLY for 2 kinds of range specifications when creating the Range Request header through the HTTPClient_AddRangeHeader function:
 

Typedefs

typedef uint32_t(* HTTPClient_GetCurrentTimeFunc_t) (void)
 Application provided function to query the current time in milliseconds.
 

Enumerations

enum  HTTPStatus_t {
  HTTPSuccess , HTTPInvalidParameter , HTTPNetworkError , HTTPPartialResponse ,
  HTTPNoResponse , HTTPInsufficientMemory , HTTPSecurityAlertExtraneousResponseData , HTTPSecurityAlertInvalidChunkHeader ,
  HTTPSecurityAlertInvalidProtocolVersion , HTTPSecurityAlertInvalidStatusCode , HTTPSecurityAlertInvalidCharacter , HTTPSecurityAlertInvalidContentLength ,
  HTTPParserPaused , HTTPParserInternalError , HTTPHeaderNotFound , HTTPInvalidResponse
}
 The HTTP Client library return status. More...
 

Functions

HTTPStatus_t HTTPClient_InitializeRequestHeaders (HTTPRequestHeaders_t *pRequestHeaders, const HTTPRequestInfo_t *pRequestInfo)
 Initialize the request headers, stored in HTTPRequestHeaders_t.pBuffer, with initial configurations from HTTPRequestInfo_t. This method is expected to be called before sending a new request.
 
HTTPStatus_t HTTPClient_AddHeader (HTTPRequestHeaders_t *pRequestHeaders, const char *pField, size_t fieldLen, const char *pValue, size_t valueLen)
 Add a header to the request headers stored in HTTPRequestHeaders_t.pBuffer.
 
HTTPStatus_t HTTPClient_AddRangeHeader (HTTPRequestHeaders_t *pRequestHeaders, int32_t rangeStartOrlastNbytes, int32_t rangeEnd)
 Add the byte range request header to the request headers store in HTTPRequestHeaders_t.pBuffer.
 
HTTPStatus_t HTTPClient_SendHttpHeaders (const TransportInterface_t *pTransport, HTTPClient_GetCurrentTimeFunc_t getTimestampMs, HTTPRequestHeaders_t *pRequestHeaders, size_t reqBodyLen, uint32_t sendFlags)
 Send the request headers in pRequestHeaders over the transport.
 
HTTPStatus_t HTTPClient_SendHttpData (const TransportInterface_t *pTransport, HTTPClient_GetCurrentTimeFunc_t getTimestampMs, const uint8_t *pData, size_t dataLen)
 Send the request body in pRequestBodyBuf over the transport.
 
HTTPStatus_t HTTPClient_Send (const TransportInterface_t *pTransport, HTTPRequestHeaders_t *pRequestHeaders, const uint8_t *pRequestBodyBuf, size_t reqBodyBufLen, HTTPResponse_t *pResponse, uint32_t sendFlags)
 Send the request headers in HTTPRequestHeaders_t.pBuffer and request body in pRequestBodyBuf over the transport. The response is received in HTTPResponse_t.pBuffer.
 
HTTPStatus_t HTTPClient_ReceiveAndParseHttpResponse (const TransportInterface_t *pTransport, HTTPResponse_t *pResponse, const HTTPRequestHeaders_t *pRequestHeaders)
 Receive the HTTP response from the network and parse it.
 
HTTPStatus_t HTTPClient_ReadHeader (const HTTPResponse_t *pResponse, const char *pField, size_t fieldLen, const char **pValueLoc, size_t *pValueLen)
 Read a header from a buffer containing a complete HTTP response. This will return the location of the response header value in the HTTPResponse_t.pBuffer buffer.
 
const char * HTTPClient_strerror (HTTPStatus_t status)
 Error code to string conversion utility for HTTP Client library.
 

Detailed Description

User facing functions of the HTTP Client library.

Function Documentation

◆ HTTPClient_InitializeRequestHeaders()

HTTPStatus_t HTTPClient_InitializeRequestHeaders ( HTTPRequestHeaders_t pRequestHeaders,
const HTTPRequestInfo_t pRequestInfo 
)

Initialize the request headers, stored in HTTPRequestHeaders_t.pBuffer, with initial configurations from HTTPRequestInfo_t. This method is expected to be called before sending a new request.

Upon return, HTTPRequestHeaders_t.headersLen will be updated with the number of bytes written.

Each line in the header is listed below and written in this order: <HTTPRequestInfo_t.pMethod> <HTTPRequestInfo_t.pPath> <HTTP_PROTOCOL_VERSION> User-Agent: <HTTP_USER_AGENT_VALUE> Host: <HTTPRequestInfo_t.pHost>

Note that "Connection" header can be added and set to "keep-alive" by activating the HTTP_REQUEST_KEEP_ALIVE_FLAG in HTTPRequestInfo_t.reqFlags.

Parameters
[in]pRequestHeadersRequest header buffer information.
[in]pRequestInfoInitial request header configurations.
Returns
One of the following:

Example

HTTPStatus_t httpLibraryStatus = HTTPSuccess;
// Declare an HTTPRequestHeaders_t and HTTPRequestInfo_t.
HTTPRequestHeaders_t requestHeaders = { 0 };
HTTPRequestInfo_t requestInfo = { 0 };
// A buffer that will fit the Request-Line, the User-Agent header line, and
// the Host header line.
uint8_t requestHeaderBuffer[ 256 ] = { 0 };
// Set a buffer to serialize request headers to.
requestHeaders.pBuffer = requestHeaderBuffer;
requestHeaders.bufferLen = 256;
// Set the Method, Path, and Host in the HTTPRequestInfo_t.
requestInfo.pMethod = HTTP_METHOD_GET;
requestInfo.methodLen = sizeof( HTTP_METHOD_GET ) - 1U;
requestInfo.pPath = "/html/rfc2616"
requestInfo.pathLen = sizeof( "/html/rfc2616" ) - 1U;
requestInfo.pHost = "tools.ietf.org"
requestInfo.hostLen = sizeof( "tools.ietf.org" ) - 1U;
httpLibraryStatus = HTTPClient_InitializeRequestHeaders( &requestHeaders,
&requestInfo );
HTTPStatus_t HTTPClient_InitializeRequestHeaders(HTTPRequestHeaders_t *pRequestHeaders, const HTTPRequestInfo_t *pRequestInfo)
Initialize the request headers, stored in HTTPRequestHeaders_t.pBuffer, with initial configurations f...
Definition: core_http_client.c:1589
#define HTTP_METHOD_GET
Definition: core_http_client.h:62
HTTPStatus_t
The HTTP Client library return status.
Definition: core_http_client.h:196
@ HTTPSuccess
The HTTP Client library function completed successfully.
Definition: core_http_client.h:207
#define HTTP_REQUEST_KEEP_ALIVE_FLAG
Set this flag to indicate that the request is for a persistent connection.
Definition: core_http_client.h:114
Represents header data that will be sent in an HTTP request.
Definition: core_http_client.h:365
size_t bufferLen
Definition: core_http_client.h:381
uint8_t * pBuffer
Buffer to hold the raw HTTP request headers.
Definition: core_http_client.h:380
Configurations of the initial request headers.
Definition: core_http_client.h:396
uint32_t reqFlags
Flags to activate other request header configurations.
Definition: core_http_client.h:422
size_t methodLen
Definition: core_http_client.h:401
const char * pMethod
The HTTP request method e.g. "GET", "POST", "PUT", or "HEAD".
Definition: core_http_client.h:400
const char * pPath
The Request-URI to the objects of interest, e.g. "/path/to/item.txt".
Definition: core_http_client.h:406
const char * pHost
The server's host name, e.g. "my-storage.my-cloud.com".
Definition: core_http_client.h:414
size_t pathLen
Definition: core_http_client.h:407
size_t hostLen
Definition: core_http_client.h:415

◆ HTTPClient_AddHeader()

HTTPStatus_t HTTPClient_AddHeader ( HTTPRequestHeaders_t pRequestHeaders,
const char *  pField,
size_t  fieldLen,
const char *  pValue,
size_t  valueLen 
)

Add a header to the request headers stored in HTTPRequestHeaders_t.pBuffer.

Upon return, pRequestHeaders->headersLen will be updated with the number of bytes written.

Headers are written in the following format:

<field>: <value>\r\n\r\n

The trailing \r\n that denotes the end of the header lines is overwritten, if it already exists in the buffer.

Note
This function validates only that \r, \n, and : are not present in pValue or pField. : is allowed in pValue.
Parameters
[in]pRequestHeadersRequest header buffer information.
[in]pFieldThe header field name to write. The data should be ISO 8859-1 (Latin-1) encoded per the HTTP standard, but the API does not perform the character set validation.
[in]fieldLenThe byte length of the header field name.
[in]pValueThe header value to write. The data should be ISO 8859-1 (Latin-1) encoded per the HTTP standard, but the API does not perform the character set validation.
[in]valueLenThe byte length of the header field value.
Returns
One of the following:

Example

HTTPStatus_t httpLibraryStatus = HTTPSuccess;
// Assume that requestHeaders has already been initialized with
// HTTPClient_InitializeRequestHeaders().
HTTPRequestHeaders_t requestHeaders;
httpLibraryStatus = HTTPClient_AddHeader( &requestHeaders,
"Request-Header-Field",
sizeof( "Request-Header-Field" ) - 1U,
"Request-Header-Value",
sizeof("Request-Header-Value") - 1U );
HTTPStatus_t HTTPClient_AddHeader(HTTPRequestHeaders_t *pRequestHeaders, const char *pField, size_t fieldLen, const char *pValue, size_t valueLen)
Add a header to the request headers stored in HTTPRequestHeaders_t.pBuffer.
Definition: core_http_client.c:1689

◆ HTTPClient_AddRangeHeader()

HTTPStatus_t HTTPClient_AddRangeHeader ( HTTPRequestHeaders_t pRequestHeaders,
int32_t  rangeStartOrlastNbytes,
int32_t  rangeEnd 
)

Add the byte range request header to the request headers store in HTTPRequestHeaders_t.pBuffer.

For example, if requesting for the first 1kB of a file the following would be written: Range: bytes=0-1023\r\n\r\n.

The trailing \r\n that denotes the end of the header lines is overwritten, if it already exists in the buffer.

There are 3 different forms of range specification, determined by the combination of rangeStartOrLastNBytes and rangeEnd parameter values:

  1. Request containing both parameters for the byte range [rangeStart, rangeEnd] where rangeStartOrLastNBytes <= rangeEnd. Example request header line: Range: bytes=0-1023\r\n for requesting bytes in the range [0, 1023].
    Example
    HTTPStatus_t httpLibraryStatus = HTTPSuccess;
    // Assume that requestHeaders has already been initialized with
    // HTTPClient_InitializeRequestHeaders().
    HTTPRequestHeaders_t requestHeaders;
    // Request for bytes 0 to 1023.
    httpLibraryStatus = HTTPClient_AddRangeHeader( &requestHeaders, 0, 1023 );
    HTTPStatus_t HTTPClient_AddRangeHeader(HTTPRequestHeaders_t *pRequestHeaders, int32_t rangeStartOrlastNbytes, int32_t rangeEnd)
    Add the byte range request header to the request headers store in HTTPRequestHeaders_t....
    Definition: core_http_client.c:1749
  2. Request for the last N bytes, represented by rangeStartOrlastNbytes. rangeStartOrlastNbytes should be negative and rangeEnd should be HTTP_RANGE_REQUEST_END_OF_FILE. Example request header line: Range: bytes=-512\r\n for requesting the last 512 bytes (or bytes in the range [512, 1023] for a 1KB sized file).
    Example
    HTTPStatus_t httpLibraryStatus = HTTPSuccess;
    // Assume that requestHeaders has already been initialized with
    // HTTPClient_InitializeRequestHeaders().
    HTTPRequestHeaders_t requestHeaders;
    // Request for the last 512 bytes.
    httpLibraryStatus = HTTPClient_AddRangeHeader( &requestHeaders, -512, HTTP_RANGE_REQUEST_END_OF_FILE)
    #define HTTP_RANGE_REQUEST_END_OF_FILE
    Flag that represents End of File byte in the range specification of a Range Request....
    Definition: core_http_client.h:189
  3. Request for all bytes (till the end of byte sequence) from byte N, represented by rangeStartOrlastNbytes. rangeStartOrlastNbytes should be >= 0 and rangeEnd should be HTTP_RANGE_REQUEST_END_OF_FILE.
    Example request header line: Range: bytes=256-\r\n for requesting all bytes after and including byte 256 (or bytes in the range [256,1023] for a 1kB sized file).
    Example
    HTTPStatus_t httpLibraryStatus = HTTPSuccess;
    // Assume that requestHeaders has already been initialized with
    // HTTPClient_InitializeRequestHeaders().
    HTTPRequestHeaders_t requestHeaders;
    // Request for all bytes from byte 256 onward.
    httpLibraryStatus = HTTPClient_AddRangeHeader( &requestHeaders, 256, HTTP_RANGE_REQUEST_END_OF_FILE)
Parameters
[in]pRequestHeadersRequest header buffer information.
[in]rangeStartOrlastNbytesRepresents either the starting byte for a range OR the last N number of bytes in the requested file.
[in]rangeEndThe ending range for the requested file. For end of file byte in Range Specifications 2. and 3., HTTP_RANGE_REQUEST_END_OF_FILE should be passed.
Returns
Returns the following status codes: HTTPSuccess, if successful. HTTPInvalidParameter, if input parameters are invalid, including when the rangeStartOrlastNbytes and rangeEnd parameter combination is invalid. HTTPInsufficientMemory, if the passed HTTPRequestHeaders_t.pBuffer contains insufficient remaining memory for storing the range request.

◆ HTTPClient_SendHttpHeaders()

HTTPStatus_t HTTPClient_SendHttpHeaders ( const TransportInterface_t pTransport,
HTTPClient_GetCurrentTimeFunc_t  getTimestampMs,
HTTPRequestHeaders_t pRequestHeaders,
size_t  reqBodyLen,
uint32_t  sendFlags 
)

Send the request headers in pRequestHeaders over the transport.

If HTTP_SEND_DISABLE_CONTENT_LENGTH_FLAG is not set in parameter sendFlags, then the Content-Length to be sent to the server is automatically written to pRequestHeaders. The Content-Length will not be written when there is no request body. If there is not enough room in the buffer to write the Content-Length then HTTPInsufficientMemory is returned. Please see HTTP_MAX_CONTENT_LENGTH_HEADER_LENGTH for the maximum Content-Length header field and value that could be written to the buffer.

The application should close the connection with the server if any of the following errors are returned:

Parameters
[in]pTransportTransport interface, see TransportInterface_t for more information.
[in]getTimestampMsFunction to retrieve a timestamp in milliseconds.
[in]pRequestHeadersRequest configuration containing the buffer of headers to send.
[in]reqBodyLenThe length of the request entity in bytes.
[in]sendFlagsFlags which modify the behavior of this function. Please see HTTPClient_Send Flags for more information.
Returns
HTTPSuccess if successful. If there was a network error or less bytes than what were specified were sent, then HTTPNetworkError is returned.

◆ HTTPClient_SendHttpData()

HTTPStatus_t HTTPClient_SendHttpData ( const TransportInterface_t pTransport,
HTTPClient_GetCurrentTimeFunc_t  getTimestampMs,
const uint8_t *  pData,
size_t  dataLen 
)

Send the request body in pRequestBodyBuf over the transport.

Parameters
[in]pTransportTransport interface, see TransportInterface_t for more information.
[in]getTimestampMsFunction to retrieve a timestamp in milliseconds.
[in]pDataHTTP request data to send.
[in]dataLenHTTP request data length.
Returns
HTTPSuccess if successful. If there was a network error or less bytes than what were specified were sent, then HTTPNetworkError is returned.

◆ HTTPClient_Send()

HTTPStatus_t HTTPClient_Send ( const TransportInterface_t pTransport,
HTTPRequestHeaders_t pRequestHeaders,
const uint8_t *  pRequestBodyBuf,
size_t  reqBodyBufLen,
HTTPResponse_t pResponse,
uint32_t  sendFlags 
)

Send the request headers in HTTPRequestHeaders_t.pBuffer and request body in pRequestBodyBuf over the transport. The response is received in HTTPResponse_t.pBuffer.

If HTTP_SEND_DISABLE_CONTENT_LENGTH_FLAG is not set in parameter sendFlags, then the Content-Length to be sent to the server is automatically written to pRequestHeaders. The Content-Length will not be written when there is no request body. If there is not enough room in the buffer to write the Content-Length then HTTPInsufficientMemory is returned. Please see HTTP_MAX_CONTENT_LENGTH_HEADER_LENGTH for the maximum Content-Length header field and value that could be written to the buffer.

The application should close the connection with the server if any of the following errors are returned:

The pResponse returned is valid only if this function returns HTTPSuccess.

Parameters
[in]pTransportTransport interface, see TransportInterface_t for more information.
[in]pRequestHeadersRequest configuration containing the buffer of headers to send.
[in]pRequestBodyBufOptional Request entity body. Set to NULL if there is no request body.
[in]reqBodyBufLenThe length of the request entity in bytes.
[in]pResponseThe response message and some notable response parameters will be returned here on success.
[in]sendFlagsFlags which modify the behavior of this function. Please see HTTPClient_Send Flags for more information.
Returns
One of the following:

Example

// Variables used in this example.
HTTPStatus_t httpLibraryStatus = HTTPSuccess;
TransportInterface_t transportInterface = { 0 };
char requestBody[] = "This is an example request body.";
// Assume that requestHeaders has been initialized with
// HTTPClient_InitializeResponseHeaders() and any additional headers have
// been added with HTTPClient_AddHeader().
HTTPRequestHeaders_t requestHeaders;
// Set the transport interface with platform specific functions that are
// assumed to be implemented elsewhere.
transportInterface.recv = myPlatformTransportReceive;
transportInterface.send = myPlatformTransportSend;
transportInterface.pNetworkContext = myPlatformNetworkContext;
// Set the buffer to receive the HTTP response message into. The buffer is
// dynamically allocated for demonstration purposes only.
response.pBuffer = ( uint8_t* )malloc( 1024 );
response.bufferLen = 1024;
httpLibraryStatus = HTTPClient_Send( &transportInterface,
&requestHeaders,
requestBody,
sizeof( requestBody ) - 1U,
&response,
0 );
if( httpLibraryStatus == HTTPSuccess )
{
if( response.status == 200 )
{
// Handle a response Status-Code of 200 OK.
}
}
HTTPStatus_t HTTPClient_Send(const TransportInterface_t *pTransport, HTTPRequestHeaders_t *pRequestHeaders, const uint8_t *pRequestBodyBuf, size_t reqBodyBufLen, HTTPResponse_t *pResponse, uint32_t sendFlags)
Send the request headers in HTTPRequestHeaders_t.pBuffer and request body in pRequestBodyBuf over the...
Definition: core_http_client.c:2209
Represents an HTTP response.
Definition: core_http_client.h:470
The transport layer interface.
Definition: transport_interface.h:299
TransportSend_t send
Definition: transport_interface.h:301
TransportRecv_t recv
Definition: transport_interface.h:300
NetworkContext_t * pNetworkContext
Definition: transport_interface.h:303

◆ HTTPClient_ReceiveAndParseHttpResponse()

HTTPStatus_t HTTPClient_ReceiveAndParseHttpResponse ( const TransportInterface_t pTransport,
HTTPResponse_t pResponse,
const HTTPRequestHeaders_t pRequestHeaders 
)

Receive the HTTP response from the network and parse it.

Parameters
[in]pTransportTransport interface, see TransportInterface_t for more information.
[in]pResponseThe response message and some notable response parameters will be returned here on success.
[in]pRequestHeadersRequest configuration containing the buffer of headers to send.
Returns
Returns HTTPSuccess if successful. HTTPNetworkError for a transport receive error. Please see parseHttpResponse and getFinalResponseStatus for other statuses returned.

◆ HTTPClient_ReadHeader()

HTTPStatus_t HTTPClient_ReadHeader ( const HTTPResponse_t pResponse,
const char *  pField,
size_t  fieldLen,
const char **  pValueLoc,
size_t *  pValueLen 
)

Read a header from a buffer containing a complete HTTP response. This will return the location of the response header value in the HTTPResponse_t.pBuffer buffer.

The location, within HTTPResponse_t.pBuffer, of the value found, will be returned in pValue. If the header value is empty for the found pField, then this function will return HTTPSuccess, and set the values for pValueLoc and pValueLen as NULL and zero respectively. According to RFC 2616, it is not invalid to have an empty value for some header fields.

Note
This function should only be called on a complete HTTP response. If the request is sent through the HTTPClient_Send function, the HTTPResponse_t is incomplete until HTTPClient_Send returns.
Parameters
[in]pResponseThe buffer containing the completed HTTP response.
[in]pFieldThe header field name to read.
[in]fieldLenThe length of the header field name in bytes.
[out]pValueLocThis will be populated with the location of the header value in the response buffer, HTTPResponse_t.pBuffer.
[out]pValueLenThis will be populated with the length of the header value in bytes.
Returns
One of the following:

Example

HTTPStatus_t httpLibraryStatus = HTTPSuccess;
// Assume that response is returned from a successful invocation of
// HTTPClient_Send().
HTTPResponse_t response;
char * pDateLoc = NULL;
size_t dateLen = 0;
// Search for a "Date" header field. pDateLoc will be the location of the
// Date header value in response.pBuffer.
httpLibraryStatus = HTTPClient_ReadHeader( &response,
"Date",
sizeof("Date") - 1,
&pDateLoc,
&dateLen );
HTTPStatus_t HTTPClient_ReadHeader(const HTTPResponse_t *pResponse, const char *pField, size_t fieldLen, const char **pValueLoc, size_t *pValueLen)
Read a header from a buffer containing a complete HTTP response. This will return the location of the...
Definition: core_http_client.c:2553

◆ HTTPClient_strerror()

const char * HTTPClient_strerror ( HTTPStatus_t  status)

Error code to string conversion utility for HTTP Client library.

Note
This returns constant strings, which should not be modified.
Parameters
[in]statusThe status code to convert to a string.
Returns
The string representation of the status code.