diff --git a/include/net/http_client.h b/include/net/http_client.h index e310aaa5fb6..4d2342ce582 100644 --- a/include/net/http_client.h +++ b/include/net/http_client.h @@ -238,7 +238,9 @@ struct http_request { /** Payload, may be NULL */ const char *payload; - /** Payload length, may be 0. Only used if payload field is not NULL */ + /** Payload length is used to calculate Content-Length. Set to 0 + * for chunked transfers. + */ size_t payload_len; /** User supplied callback function to call when optional headers need diff --git a/subsys/net/lib/http/http_client.c b/subsys/net/lib/http/http_client.c index 9f34075c626..56df15c97b4 100644 --- a/subsys/net/lib/http/http_client.c +++ b/subsys/net/lib/http/http_client.c @@ -563,9 +563,27 @@ int http_client_req(int sock, struct http_request *req, total_sent += ret; } - if (req->payload_cb) { - ret = http_send_data(sock, send_buf, send_buf_max_len, + if (req->payload || req->payload_cb) { + if (req->payload_len) { + char content_len_str[HTTP_CONTENT_LEN_SIZE]; + + ret = snprintk(content_len_str, HTTP_CONTENT_LEN_SIZE, + "%zd", req->payload_len); + if (ret <= 0 || ret >= HTTP_CONTENT_LEN_SIZE) { + ret = -ENOMEM; + goto out; + } + + ret = http_send_data(sock, send_buf, send_buf_max_len, + &send_buf_pos, + "Content-Length", ": ", + content_len_str, HTTP_CRLF, + HTTP_CRLF, NULL); + } else { + ret = http_send_data(sock, send_buf, send_buf_max_len, &send_buf_pos, HTTP_CRLF, NULL); + } + if (ret < 0) { goto out; } @@ -580,39 +598,29 @@ int http_client_req(int sock, struct http_request *req, send_buf_pos = 0; total_sent += ret; - ret = req->payload_cb(sock, req, user_data); - if (ret < 0) { - goto out; - } - - total_sent += ret; - } else if (req->payload) { - char content_len_str[HTTP_CONTENT_LEN_SIZE]; + if (req->payload_cb) { + ret = req->payload_cb(sock, req, user_data); + if (ret < 0) { + goto out; + } - ret = snprintk(content_len_str, HTTP_CONTENT_LEN_SIZE, - "%zd", req->payload_len); - if (ret <= 0 || ret >= HTTP_CONTENT_LEN_SIZE) { - ret = -ENOMEM; - goto out; - } + total_sent += ret; + } else { + u32_t length; - ret = http_send_data(sock, send_buf, send_buf_max_len, - &send_buf_pos, "Content-Length", ": ", - content_len_str, HTTP_CRLF, - HTTP_CRLF, NULL); - if (ret < 0) { - goto out; - } + if (req->payload_len == 0) { + length = strlen(req->payload); + } else { + length = req->payload_len; + } - total_sent += ret; + ret = sendall(sock, req->payload, length); + if (ret < 0) { + goto out; + } - ret = http_send_data(sock, send_buf, send_buf_max_len, - &send_buf_pos, req->payload, NULL); - if (ret < 0) { - goto out; + total_sent += length; } - - total_sent += ret; } else { ret = http_send_data(sock, send_buf, send_buf_max_len, &send_buf_pos, HTTP_CRLF, NULL);