TuyaOS
结构体 | 宏定义 | 类型定义 | 枚举 | 函数
httpc.h 文件参考

HTTP Client Module 更多...

#include <time.h>
#include "tal_time_service.h"
#include "tal_network.h"
#include "tuya_tls.h"
httpc.h 的引用(Include)关系图:
此图展示该文件直接或间接的被哪些文件引用了:

浏览源代码.

结构体

struct  parsed_url_t
 

宏定义

#define HTTP_ACCEPTED   202
 
#define HTTP_BAD_REQUEST   400
 
#define HTTP_CREATED   201
 
#define HTTP_FORBIDDEN   403
 
#define HTTP_FOUND   302
 
#define HTTP_NOT_AUTH   401
 
#define HTTP_NOT_FOUND   404
 
#define HTTP_NOT_MODIFIED   304
 
#define HTTP_OK   200
 
#define HTTP_RESP_CLIENT_ERR(x)   (x >= 400 && x < 500)
 
#define HTTP_RESP_INFORMATIONAL(x)   (x >=100 && < 200)
 
#define HTTP_RESP_REDIR(x)   (x >= 300 && x < 400)
 
#define HTTP_RESP_SERVER_ERR(x)   (x >= 500 && x < 600)
 
#define HTTP_RESP_SUCCESS(x)   (x >= 200 && x < 300)
 
#define PARSE_EXTRA_BYTES   10
 
#define REDIRECT_CNT_DEFAULT   3
 
#define REDIRECT_CNT_DISABLED   0
 
#define REDIRECT_CNT_MAX   5
 
#define STANDARD_HDR_FLAGS    (HDR_ADD_DEFAULT_USER_AGENT)
 

类型定义

typedef int(* HTTP_CUSTOM_AFTER_READ_CONTENT_CB) (VOID *pri_data)
 
typedef int(* HTTP_CUSTOM_BEFORE_READ_CONTENT_CB) (VOID *pri_data, unsigned int *p_malloc_buffer_size)
 
typedef unsigned int(* HTTP_CUSTOM_GET_CONTENT_LEN_CB) (VOID *pri_data)
 
typedef int(* HTTP_CUSTOM_READ_CONTENT_CB) (unsigned char *p_buffer, int buf_size, VOID *pri_data)
 
typedef void(* HTTP_HEAD_ADD_CB) (http_session_t session, VOID *data)
 
typedef void * http_session_t
 

枚举

enum  http_hdr_field_sel_t {
  HDR_ADD_DEFAULT_USER_AGENT = 0x0001 , HDR_ADD_CONN_KEEP_ALIVE = 0x0002 , HDR_ADD_CONN_CLOSE = 0x0004 , HDR_ADD_TYPE_CHUNKED = 0x0008 ,
  HDR_ADD_CONTENT_TYPE_JSON = 0x0010 , HDR_ADD_CONTENT_TYPE_FORM_URLENCODE = 0x0020 , HRD_ADD_DOWNLOAD_RANGE = 0x0040 , HRD_ADD_HTTP_RAW = 0x0080
}
 
enum  http_method_t {
  HTTP_OPTIONS , HTTP_GET , HTTP_HEAD , HTTP_POST ,
  HTTP_PUT , HTTP_DELETE , HTTP_TRACE , HTTP_CONNECT
}
 
enum  http_open_flags_t { TLS_ENABLE = 0x01 }
 
enum  http_ver_t { HTTP_VER_1_0 , HTTP_VER_1_1 }
 
enum  wm_httpc_errno {
  WM_SUCCESS = 0 , WM_E_INVAL , WM_FAIL , WM_E_IO ,
  WM_E_AGAIN , WM_E_BADF , WM_E_NOMEM , WM_E_HTTPC_TCP_CONNECT_FAIL ,
  WM_E_HTTPC_TCP_TLS_CONNECT_FAIL , WM_E_HTTPC_FILE_NOT_FOUND , WM_E_HTTPC_BAD_REQUEST , WM_E_HTTPC_TLS_NOT_ENABLED ,
  WM_E_HTTPC_SOCKET_ERROR , WM_E_HTTPC_SOCKET_SHUTDOWN , WM_E_HTTPC_SOCKET_TIMEOUT , WM_E_HTTPC_DNS_PARSE_FAILED ,
  WM_E_HTTPC_SOCKET_CREAT_FAILED , WM_E_HTTPC_URL_PARSE_FAILED
}
 

函数

int http_add_header (http_session_t handle, const http_req_t *req, const char *name, const char *value)
 
void http_close_session (http_session_t *handle)
 
int http_get_response_hdr (http_session_t handle, http_resp_t **resp)
 
int http_get_response_hdr_all (http_session_t handle, http_header_pair_t *arr, int *count)
 
int http_get_response_hdr_value (http_session_t handle, const char *header_name, char **value)
 
BOOL_T http_is_session_closed (http_session_t *handle)
 
int http_lowlevel_read (http_session_t handle, void *buf, unsigned maxlen)
 
int http_lowlevel_write (http_session_t handle, const void *buf, unsigned len)
 
int http_open_session (http_session_t *handle, const char *hostname, int flags, int retry_cnt)
 
int http_open_session_with_config (http_session_t *handle, const char *hostname, tuya_tls_config_t *tls_config, int flags, int retry_cnt)
 
int http_parse_URL (const char *URL, char *tmp_buf, int tmp_buf_len, parsed_url_t *parsed_url)
 
int http_prepare_req (http_session_t handle, const http_req_t *req, http_hdr_field_sel_t field_flags)
 
int http_read_content (http_session_t handle, void *buf, unsigned int max_len)
 
UINT8_T http_recv_timeout_get (void)
 This API is used to GET HTTP recv timeout 更多...
 
OPERATE_RET http_recv_timeout_set (IN UINT8_T timeout_s)
 This API is used to SET HTTP recv timeout 更多...
 
UINT8_T http_redirect_limit_get (void)
 This API is used to GET HTTP Redirect Limit Count 更多...
 
OPERATE_RET http_redirect_limit_set (IN UINT8_T cnt)
 This API is used to SET HTTP Redirect Limit Count 更多...
 
void http_reset_session_state (http_session_t handle)
 
int http_send_request (http_session_t handle, const http_req_t *req, int send_content)
 
int http_write_standard (http_session_t handle, const void *buf, unsigned len)
 
int httpc_write_chunked (http_session_t handle, const char *data, int len)
 

详细描述

HTTP Client Module

The HTTP Client module is a software component layered atop basic BSD socket API and CyaSSL (a TLS library). The HTTP Client module (hereafter called the module) provides a set of API and data structures to provide an easy way of communication with any web server supporting the HTTP protocol.

Some examples of the HTTP client users (hereafter called the users) of this module are: an email client, a websockets library, OTA firmware upgrade module, and all the myriad web services users.

The module implements a session based API. The users open a session with the server which internally sets up a TCP stream with the server. The user gets a handle to this session. All the other operations viz. sending HTTP headers, sending HTTP content, reading HTTP content, etc. are then performed on the same session through the session handle. The server also supports multiple HTTP transactions on the same server (which uses the keep-alive mechanism through persistent connections). A transaction is defined as a request and a response activity. Interleaved transactions are also supported. The module also supports chunked encoding transparently to the user.

An important feature supported by the module is HTTPS connections. This allows a user to perform his HTTP transactions securely. To help support this the module works with an external TLS library. During session open, the user optionally needs to supply a root certificate to verify the server certificate. The user can also provide the module with its own client certificate if the server is expected to do client verification. Apart from session the initialization API, the remaining API's handle secure and non-secure connections transparently to the user.

Lastly, the module also provides some API's to deal with HTTP session directly. i.e. it provides users access to the socket directly.

Usage

A typical HTTP Client usage scenario is as follows:

  1. Initiate a connection with the remote Web Server using a call to http_open_session().
  2. Prepare the request with a call the API to http_prepare_req().
  3. Send one or more (for interleaved mode) HTTP requests to the server using the APIs http_prepare_req() and http_send_request() pair together.
  4. An optional call the API to API http_get_response_hdr() can be made if the application wishes to know certain fields of the HTTP response.
  5. Then multiple calls of API http_read_content() are made for reading the response from the remote Web Server.
  6. The connection with the remote server is terminated using the API http_close_session()

枚举类型说明

◆ http_hdr_field_sel_t

The OR of zero or more flags below is passed to the API http_prepare_req(). If the a flag is passed the corresponding HTTP header field is added to the HTTP header. The values added will be default ones.

◆ http_open_flags_t

If the given URL has a scheme field, and it is https then the http client will auto-switch to SSL mode, irrespective of the TLS_ENABLE flag below.

枚举值
TLS_ENABLE 

Pass this flag when you want the connection to be SSL based

◆ wm_httpc_errno

HTTPC Error Codes

枚举值
WM_E_HTTPC_TCP_CONNECT_FAIL 

TCP connection failed (maybe due to unreachable server)

WM_E_HTTPC_TCP_TLS_CONNECT_FAIL 

TCP tls connection failed (maybe due to unreachable server)

WM_E_HTTPC_FILE_NOT_FOUND 

HTTP File not found

WM_E_HTTPC_BAD_REQUEST 

HTTP Bad Request

WM_E_HTTPC_TLS_NOT_ENABLED 

TLS not enabled

WM_E_HTTPC_SOCKET_ERROR 

Socket error. Note to applications: Please check 'errno' for more information

WM_E_HTTPC_SOCKET_SHUTDOWN 

Peer has performed orderly shutdown

函数说明

◆ http_add_header()

int http_add_header ( http_session_t  handle,
const http_req_t req,
const char *  name,
const char *  value 
)

Add custom http headers to the partially generated header.

This API allows the caller to add custom headers to the partial http header generated by earlier call to http_prepare_req()

注解
Calling this API is optional and needs to be called only if custom headers (or standard headers with non-default values) are to be added.
前置条件
http_prepare_req()
参数
[in]handleHandle returned from the call to http_open_session()
[in]reqStructure of the type http_req_t passed earlier to http_prepare_req()
[in]nameThe name of the field. e.g User-Agent or If-Modified-Since
[in]valueValue associated with the name given above.
返回
Standard wmsdk value.

◆ http_close_session()

void http_close_session ( http_session_t *  handle)

Close the session.

This API will close the session represented by the given handle. The socket associated with this session will be closed and thus the TCP connection with the server will be terminated. No requests on this same session will succeed after this API is called.

注解
The response structure http_resp_t returned earlier from http_get_response_hdr() will be invalid after this call.
参数
[in]handleHandle returned from the previous call to http_new_session(). The handle will be set to NULL by the callee thus effectively blocking futher requests on the same session handle.

◆ http_get_response_hdr()

int http_get_response_hdr ( http_session_t  handle,
http_resp_t **  resp 
)

Get the HTTP response header

This API received the response header from the server and parses it. It then populates the http_resp_t structure and returns the pointer to this structure. The structure http_resp_t is allocated by the callee.

The caller is expected to analyse this information to find out the result of the earlier request sent through API http_send_request(). If the earlier request was HTTP_GET then the caller will need to call the API http_read_content() to read the data sent by the server.
注解
Calling this API is optional. If the caller does not want to read/analyse the header and knows beforehand what to expect, it can directly call http_read_content(). The API http_read_content() will internally read the HTTP response header. However, the API http_read_content() will return an error if the HTTP status code returned is not 200. If you need to read content in cases where the return status code is other than 200 you need to call http_get_response_hdr() first.
After invoking this API, it is mandatory to read the entire content using the http_read_content() API, especially in the case of repeat http transaction on the same session handle (interleaved mode).
If this API fails and the caller decides to abandon this session altogether it needs to call http_close_session() explicitly. Failure to do this will cause undefined behaviour.
前置条件
http_send_request() is called before.
参数
[in]handleHandle returned from the call to http_new_session()
[in,out]respPointer to a pointer of type http_resp_t .The structure will be allocated by the callee. Note that the caller does not need to free the structure allocated and returned from this API. The allocation and free is done by the callee automatically.
返回
WM_SUCCESS on success
-WM_FAIL on error

◆ http_get_response_hdr_all()

int http_get_response_hdr_all ( http_session_t  handle,
http_header_pair_t arr,
int *  count 
)

Get requested number of HTTP response header name-value pairs.

This API parses the response header received from the server and returns requested number of HTTP response header name-value pairs.
The caller is not expected to call API http_get_response_hdr() before this. However, calling http_get_response_hdr is recommended so that the user gets to know the exact status of the HTTP operation before he tries to extract any field not present in structure http_resp_t
注解
Calling this API is optional. If the caller does not want to read/analyse the header and knows beforehand what to expect, s/he can directly call http_read_content(). The API http_read_content() will internally read the HTTP response header. However, the API http_read_content() will return an error if the HTTP status code returned is not 200. If you need to read content in cases where the return status code is other than 200 you need to call http_get_response_hdr() or the current API first.
If this API fails and the caller decides to abandon this session altogether it needs to call http_close_session() explicitly. Failure to do this will cause undefined behaviour.
前置条件
http_send_request() is called before this call. Calling http_get_response_hdr() is not mandatory but recommended.
参数
[in]handleHandle returned from the call to http_new_session()
[in,out]arrA pointer that points to an array of the structure to hold the response header name-value pairs. This array needs to be pre-allocated and its pointer is to be passed, this pointer shall point to the array of requested number of response header name-value pairs.
[in,out]countAn integer pointer that points to the number of response header name-value pairs that the user wants. This has to be passed by the user and it is later updated to the actual number of response header name-value pairs that were filled in the array mentioned above.
返回
WM_SUCCESS on success
-WM_FAIL on error

◆ http_get_response_hdr_value()

int http_get_response_hdr_value ( http_session_t  handle,
const char *  header_name,
char **  value 
)

Get a particular HTTP response header value.

This API parses the response header received from the server and returns the value corresponding to a given name. This can help the caller get value of a particular field not parsed automatically in http_resp_t

The caller is not expected to call http_get_response_hdr() before this. However, calling http_get_response_hdr() is recommended so that the user gets to know the exact status of the HTTP operation before he tries to extract any field not present in structure http_resp_t
注解
Calling this API is optional. If the caller does not want to read/analyse the header and knows beforehand what to expect, it can directly call http_read_content(). The API http_read_content() will internally read the HTTP response header. However, the API http_read_content() will return an error if the HTTP status code returned is not 200. If you need to read content in cases where the return status code is other than 200 you need to call http_get_response_hdr() or the current API first.
If this API fails and the caller decides to abandon this session altogether it needs to call http_close_session() explicitly. Failure to do this will cause undefined behaviour.
前置条件
http_send_request is called before this call. Calling http_get_response_hdr() is not mandatory but recommended.
参数
[in]handleHandle returned from the call to http_new_session
[in]header_nameThe name of the field whose value you wish to know
[in,out]valueA pointer which will point to the value corresponding to the name passed as second parameter.
返回
WM_SUCCESS on success
-WM_FAIL on error

◆ http_is_session_closed()

BOOL_T http_is_session_closed ( http_session_t *  handle)

Check wether the session is closed.

This API checks to see if a given session handle is closed.

参数
[in]handleHandle returned from the call to http_new_session()
返回
TRUE if the given session handle is closed, FALSE otherwise

◆ http_lowlevel_read()

int http_lowlevel_read ( http_session_t  handle,
void *  buf,
unsigned  maxlen 
)

HTTP lowlevel read

This API is present to serve clients which want to handle the HTTP stream directly. This is useful for handling websockets for e.g.

警告
This is not for general users of HTTP client API. Normal HTTP transactions do not need this API.
注解
Once this API used no other API from the HTTP API set, except http_close_session(), can be used. This is because once this API is used the HTTP client loses track of the stream and only the caller using the API can know the state of the stream. The only advantage of using this API over normal socket read/write is that this API transparently takes care of TLS and non-TLS interface to read/write.
参数
[in]handleHandle returned from the call to http_new_session()
[in,out]bufPointer to an allocated buffer of size equal to or more than the value of the third parameter maxlen
[in]maxlenThe maximum number of bytes to be read from the network. Note that the actual read bytes can be less than this.
返回
Number of bytes read. -WM_E_INVAL is returned in case of invalid parameters. Standard libc error codes are returned in case when there other problems.

◆ http_lowlevel_write()

int http_lowlevel_write ( http_session_t  handle,
const void *  buf,
unsigned  len 
)

HTTP lowlevel write

This API is present to serve clients which want to handle the HTTP stream directly. This is useful for handling websockets for e.g.

警告
This is not for general users of HTTP client API. Normal HTTP transactions do not need this API.
注解
Once this API used no other API from the HTTP API set, except http_close_session, can be used. This is because once this API is used the HTTP client loses track of the stream and only the caller using the API can know the state of the stream. The only advantage of using this API over normal socket read/write is that this API transparently takes care of TLS and non-TLS interface to read/write.
参数
[in]handleHandle returned from the call to http_new_session()
[in,out]bufPointer to a buffer which has the data to be written out.
[in]lenThe number of bytes to be written to the network.
返回
Number of bytes written. -WM_E_INVAL is returned in case of invalid parameters. Standard libc error codes are returned in case when there other problems.

◆ http_open_session()

int http_open_session ( http_session_t *  handle,
const char *  hostname,
int  flags,
int  retry_cnt 
)

Start an HTTP session.

This API starts a new HTTP session. It will create a socket and then connect to the server given as a parameter.
参数
[in,out]handlePointer to a handle for the session. Will be assigned by the callee.
[in]hostnameHost name or IP address. The hostname should be in the format [http://]hostname[:portno][/path/to/resource]. The fields between the square brackets above are optional. The part specifying the path to resource will be ignored as it is of no use during session setup.
[in]flagsPass OR of the flags mentioned in enum http_open_flags_t.
[in]cfgThis is a pointer of the type tls_init_config_t. Please refer to file wm-tls.h for the structure internals. This pointer will be passed verbatim to the tls API tls_session_init(). If TLS (secure connection) is not needed please pass NULL value.
[in]retry_cntThere are limited sockets available due to memory constraints. A socket creation can fail if all sockets are currently used up. If the socket creation fails, http_open_session() will wait for some time and try to create the socket again for retry_cnt number of times. 0 is default value which lets the SDK decide the count.
返回
WM_SUCCESS on success
-WM_E_INVAL if any of the arguments were invalid
-WM_FAIL if the API was unable to initiate an HTTP session with the server.

◆ http_parse_URL()

int http_parse_URL ( const char *  URL,
char *  tmp_buf,
int  tmp_buf_len,
parsed_url_t parsed_url 
)

Parse the given string into URL subcomponents.

The hostname string syntax is: [scheme://]hostname[:port][/path_to_resource?query_string::fragment_id] The fields between the square brackets above are optional.

注解
Buffer management: To free the caller of the task of allocating multiple buffers of arbitrary size to store each of the subcomponents we use the following strategy. This API takes a temporary buffer, allocated (static or dynamic) by the caller to store the subcomponents. The caller needs to allocate this buffer with size equal to (strlen(URL) + 10). When this API returns, the pointers in the parsed_url structure will point to appropriate address in this buffer. The caller may free this buffer after usage of the sub-components is complete. Freeing before that will cause undefined behavior.
参数
[in]URLPointer to the string containing the URL. This API will not modify this argument.
[in]tmp_bufA buffer where the strings will be stored after parsing. Needs to be allocated by the caller and should be of size atleast 10 greater than size of the URL string passed as first argument.
[in]tmp_buf_lenSize of the caller allocated, temporary buffer sent as second argument.
[in,out]parsed_urlPointer to an allocated structure. The member pointers will point to the appropriate address in the temporary buffer holding the NULL terminated string corresponding to the subcomponent.
返回
Standard WMSDK return codes.

◆ http_prepare_req()

int http_prepare_req ( http_session_t  handle,
const http_req_t req,
http_hdr_field_sel_t  field_flags 
)

Prepare the HTTP header for sending to the server.

This API will prepare an HTTP request for sending it out through http_send_request(). Calling this API is mandatory before calling http_send_request().

前置条件
http_open_session()
参数
[in]handleHandle returned from the call to http_open_session()
[in]reqAllocated and initialized http_req_t structure.
[in]field_flagsBitwise OR of flags of enum http_hdr_field_sel_t as required by the caller.
注解
The request structure http_req_t needs to be filled before invoking this API.
The field_flags parameter is a way to request the http client to use default field values for standard fields. If the corresponding bits are not set then the respective fields are not added. The user can add any custom fields including the standard ones using the API http_add_header()
返回
Standard wmsdk return codes.

◆ http_read_content()

int http_read_content ( http_session_t  handle,
void *  buf,
unsigned int  max_len 
)

Read data content from the stream.

This API will read the data sent by the server and pass it back to the caller.

The data transfer from the server to the client may be chunked. This fact will be reported in the response structure http_resp_t returned in a previous call to http_get_response_hdr(). Notwithstanding this information, chunked data handling is transparent to the caller. Thus, irrespective of the transfer type, this API should be called repeatedly till the return value of the API is zero.
注解
Once you start reading the content, it is mandatory to read the entire content before you begin the next HTTP transaction.
If this API fails and the caller decides to abandon this session altogether it needs to call http_close_session() explicitly. Failure to do this will cause undefined behaviour.
参数
[in]handleHandle returned from the call to http_new_session()
[in,out]bufCaller allocated buffer of size max_len
[in]max_lenSize of the buffer. The data read will be less than or equal to this size, depending on the size of the resource.
返回
On success, the number of bytes read is returned. Return value of zero is not an error case and should be treated as a signal that server is done with sending the data.
-WM_FAIL if this API is called again after the previous call retuned 0 or for any other error.

◆ http_recv_timeout_get()

UINT8_T http_recv_timeout_get ( void  )

This API is used to GET HTTP recv timeout

参数
[in]
返回
count of http redirect

◆ http_recv_timeout_set()

OPERATE_RET http_recv_timeout_set ( IN UINT8_T  timeout_s)

This API is used to SET HTTP recv timeout

参数
[in]timeout_stimeout (unit:s)
返回
OPRT_OK on success. Others on error, please refer to tuya_error_code.h

◆ http_redirect_limit_get()

UINT8_T http_redirect_limit_get ( void  )

This API is used to GET HTTP Redirect Limit Count

参数
[in]
返回
count of http redirect

◆ http_redirect_limit_set()

OPERATE_RET http_redirect_limit_set ( IN UINT8_T  cnt)

This API is used to SET HTTP Redirect Limit Count

参数
[in]cntThe count of redirect, the max value should <= REDIRECT_CNT_MAX Set as zero, means disable http redirect function.
返回
OPRT_OK on success. Others on error, please refer to tuya_error_code.h

◆ http_send_request()

int http_send_request ( http_session_t  handle,
const http_req_t req,
int  send_content 
)

Perform an HTTP request.

This API sends the prepared request header and content if applicable.

注解
If this API fails and the caller decides to abandon this session altogether it needs to call the API http_close_session() explicitly. Failure to do this will cause undefined behaviour.
前置条件
http_prepare_req() is mandatory. http_add_header() is optional.
参数
[in]handleHandle returned from the call to http_open_session()
[in]reqThe http_req_t structure filled up with appropriate parameters.
返回
WM_SUCCESS on success
-WM_E_IO if failed to send data to network
-WM_E_INVAL for an invalid arguments.

◆ httpc_write_chunked()

int httpc_write_chunked ( http_session_t  handle,
const char *  data,
int  len 
)

HTTP write chunked

This API is used for chunked transfer encoding

注解
To end the chunked data transfer, this API should be called with len=0, buf may be NULL
参数
[in]handleHandle retrieved from the call to http_open_session()
[in]dataPointer to the buffer to be written.
[in]lenThe number of bytes to be written.
返回
WM_SUCCESS is returned on success.
-WM_E_INVAL is returned in case of invalid parameters.
-WM_FAIL is returned if session is invalid.
Standard libc error codes are returned when there are other problems.