Logo Pico-Framework A web-first embedded framework for C++
Loading...
Searching...
No Matches
HttpRequest Class Reference

Forward declaration for potential routing needs. More...

#include <HttpRequest.h>

+ Collaboration diagram for HttpRequest:

Public Member Functions

 HttpRequest (const char *rawHeaders, const std::string &reqMethod, const std::string &reqPath)
 Construct a HttpRequest from raw headers, method, and path.
 
 HttpRequest (const std::string &raw, const std::string &method, const std::string &path)
 
 HttpRequest (Tcp *connection, const std::string rawHeaders, const std::string &method, const std::string &path)
 
 HttpRequest ()=default
 
 HttpRequest (const HttpRequest &)=default
 
HttpRequestsetRootCACertificate (const std::string &certData)
 Set the root CA certificate to use for TLS.
 
HttpResponse send ()
 Send the request and return the response.
 
HttpResponse get ()
 Send a GETPOST/PUT/DEL request.
 
HttpResponse get (const std::string &url)
 
HttpResponse post ()
 
HttpResponse post (const std::string &url, const std::string &body)
 
HttpResponse put ()
 
HttpResponse put (const std::string &url, const std::string &body)
 
HttpResponse del ()
 
HttpResponse del (const std::string &url)
 
std::string getHeader (const std::string &field) const
 Get a specific header field (case-insensitive).
 
const std::map< std::string, std::string > & getHeaders () const
 Get all request headers.
 
void printHeaders () const
 Print all headers to the standard output.
 
void setHeaderEnd (size_t end)
 Set the position marking the end of headers.
 
size_t getHeaderEnd ()
 Get the header end offset (used for body parsing).
 
const std::string & getHost () const
 Get the Host header value.
 
const std::string & getProtocol () const
 
bool isFormUrlEncoded () const
 Check if content-type is application/x-www-form-urlencoded.
 
bool isJson () const
 Check if content-type is application/json.
 
const std::string getContentType () const
 Get the raw Content-Type string.
 
const std::string getBoundary () const
 Get the boundary string (for multipart/form-data).
 
bool isMultipart () const
 Check whether the request is multipart/form-data.
 
const std::string & getBody () const
 Get the request body (copy).
 
bool isBodyTruncated () const
 Check if the request body was truncated due to memory limits.
 
void markBodyTruncated ()
 
HttpRequestsetBody (const std::string &body)
 Set the body of the request.
 
HttpRequestsetJson (const nlohmann::json &json)
 Set the body of the request as JSON.
 
HttpRequestsetJson (const std::string &json)
 Set the body of the request as JSON.
 
int getContentLength () const
 Get the Content-Length header as integer.
 
nlohmann::json json () const
 Safely parse the request body as JSON (non-throwing).
 
HttpRequestsetMethod (const std::string &method)
 Set the HTTP method (e.g., GET, POST).
 
HttpRequestsetPath (const std::string &path)
 Set the request path.
 
const std::string & getMethod () const
 Get the HTTP method.
 
const std::string & getPath () const
 Get the parsed request path (without query string).
 
const std::string & getUri () const
 Get the original URL from the request line.
 
const std::string & getQuery () const
 Get the parsed query string from the URL.
 
TcpgetTcp () const
 
const std::unordered_map< std::string, std::string > getCookies () const
 Get all parsed cookies.
 
const std::string getCookie (const std::string &name) const
 Get a specific cookie value.
 
const std::unordered_multimap< std::string, std::string > getQueryParams ()
 Get parsed query string parameters.
 
const std::unordered_multimap< std::string, std::string > getFormParams ()
 Get parsed form fields (application/x-www-form-urlencoded).
 
bool appendRemainingBody (int expectedLength)
 
int handle_multipart (HttpResponse &res)
 Handle multipart/form-data uploads.
 
HttpRequestsetUri (const std::string &uri)
 Set the URI for the request.
 
HttpRequestsetHost (const std::string &host)
 
HttpRequestsetProtocol (const std::string &protocol)
 
HttpRequestsetHeaders (const std::map< std::string, std::string > &headers)
 
HttpRequestsetHeader (const std::string &key, const std::string &value)
 
HttpRequestsetUserAgent (const std::string &userAgent)
 
HttpRequestsetAcceptEncoding (const std::string &encoding)
 
HttpRequesttoFile (const std::string &path)
 
std::string getOutputFilePath () const
 
bool wantsToFile () const
 
const std::string & getRootCACertificate () const
 Get the root CA certificate string, if set.
 

Static Public Member Functions

static HttpRequest receive (Tcp *tcp)
 Receive and parse an HTTP request from a socket.
 
static std::optional< std::pair< std::string, std::string > > receiveUntilHeadersComplete (Tcp *conn)
 
static bool getMethodAndPath (const std::string &data, std::string &method, std::string &path)
 Parse the HTTP method and path from the first request line.
 
static HttpRequest create ()
 

Private Member Functions

void parseHeaders (const char *raw)
 
void appendToBody (const char *data, size_t len)
 
void setQueryString (const std::string &query)
 

Private Attributes

Tcptcp = nullptr
 
std::string clientIp
 
std::string method
 
std::string uri
 
std::string path
 
std::string query
 
std::string host
 
std::string protocol
 
std::map< std::string, std::string > headers
 
std::string body
 
std::string rootCACertificate
 
size_t headerEnd = 0
 
bool bodyTruncated = false
 
std::string outputFilePath
 

Detailed Description

Represents a parsed HTTP request, providing access to headers, method, path, body, etc.

Examples
/home/runner/work/pico-framework-docs/pico-framework-docs/pico-framework/framework/include/http/Middleware.h.

Definition at line 31 of file HttpRequest.h.

Constructor & Destructor Documentation

◆ HttpRequest() [1/5]

HttpRequest::HttpRequest ( const char *  rawHeaders,
const std::string &  reqMethod,
const std::string &  reqPath 
)

Construct a HttpRequest object and parse the URL and headers.

Parameters
rawHeadersRaw HTTP headers as a C-string.
reqMethodHTTP method.
reqPathHttpRequest path.
rawHeadersRaw header string.
reqMethodHTTP method (GET, POST, etc.).
reqPathHttpRequest URL path.

Definition at line 120 of file HttpRequest.cpp.

121 : method(reqMethod), path(reqPath)
122{
123
124 uri = reqPath; // Store the original URL
125 // Parse the URL to separate path and query string
126 size_t pos = uri.find('?');
127 if (pos != std::string::npos)
128 {
129 path = uri.substr(0, pos);
130 query = uri.substr(pos + 1);
131 }
132 else
133 {
134 path = uri;
135 query = "";
136 }
137 parseHeaders(rawHeaders);
138}
std::string uri
void parseHeaders(const char *raw)
std::string query
std::string method
std::string path

References parseHeaders(), path, query, and uri.

+ Here is the call graph for this function:

◆ HttpRequest() [2/5]

HttpRequest::HttpRequest ( const std::string &  raw,
const std::string &  method,
const std::string &  path 
)
inline

Definition at line 47 of file HttpRequest.h.

48 : method(method), uri(path), path(path) {}

◆ HttpRequest() [3/5]

HttpRequest::HttpRequest ( Tcp connection,
const std::string  rawHeaders,
const std::string &  method,
const std::string &  path 
)
inline

Definition at line 51 of file HttpRequest.h.

52 : tcp(connection), method(method), uri(path), path(path)
53 {
54 parseHeaders(rawHeaders.c_str());
55 }

References parseHeaders().

+ Here is the call graph for this function:

◆ HttpRequest() [4/5]

HttpRequest::HttpRequest ( )
default

Referenced by create(), and receive().

+ Here is the caller graph for this function:

◆ HttpRequest() [5/5]

HttpRequest::HttpRequest ( const HttpRequest )
default

Member Function Documentation

◆ appendRemainingBody()

bool HttpRequest::appendRemainingBody ( int  expectedLength)

Definition at line 224 of file HttpRequest.cpp.

224 {
225 size_t remaining = expectedLength - body.size();
226 char buffer[HTTP_BUFFER_SIZE];
227
228 while (remaining > 0) {
229 size_t toRead = std::min(remaining, sizeof(buffer));
230 int received = tcp->recv(buffer, toRead, HTTP_RECEIVE_TIMEOUT);
231 if (received <= 0) {
232 printf("Error receiving body chunk\n");
233 return false;
234 }
235 size_t currentSize = body.size();
236 if (currentSize >= MAX_HTTP_BODY_LENGTH) {
237 TRACE("Body exceeds max length. Truncating.\n");
239 break;
240 }
241 size_t allowed = MAX_HTTP_BODY_LENGTH - currentSize;
242 size_t toAppend = std::min(static_cast<size_t>(received), allowed);
243 body.append(buffer, toAppend);
244
245 if (toAppend < static_cast<size_t>(received)) {
246 TRACE("Body chunk truncated due to size limit.\n");
248 break;
249 }
250 remaining -= received;
251 }
252 return true;
253}
#define TRACE(...)
Default trace (INFO level).
Definition DebugTrace.h:187
std::string body
void markBodyTruncated()
int recv(char *buffer, size_t size, uint32_t timeout_ms)
Receive data from the connection.
Definition Tcp.cpp:389
#define HTTP_BUFFER_SIZE
Size of the HTTP buffer for request/response data.
#define HTTP_RECEIVE_TIMEOUT
Timeout for receiving HTTP data in milliseconds.
#define MAX_HTTP_BODY_LENGTH
Maximum HTTP body size in bytes.

References body, HTTP_BUFFER_SIZE, HTTP_RECEIVE_TIMEOUT, markBodyTruncated(), MAX_HTTP_BODY_LENGTH, Tcp::recv(), tcp, and TRACE.

Referenced by receive().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ appendToBody()

void HttpRequest::appendToBody ( const char *  data,
size_t  len 
)
private

◆ create()

HttpRequest HttpRequest::create ( )
static

Definition at line 412 of file HttpRequest.cpp.

413{
414 return HttpRequest("", "", "");
415}
HttpRequest()=default

References HttpRequest().

+ Here is the call graph for this function:

◆ del() [1/2]

HttpResponse HttpRequest::del ( )

Definition at line 71 of file HttpRequest.cpp.

72{
73 setMethod("DELETE");
74 return send();
75}
HttpRequest & setMethod(const std::string &method)
Set the HTTP method (e.g., GET, POST).
HttpResponse send()
Send the request and return the response.

References send(), and setMethod().

+ Here is the call graph for this function:

◆ del() [2/2]

HttpResponse HttpRequest::del ( const std::string &  url)

Definition at line 93 of file HttpRequest.cpp.

94{
95 setMethod("DELETE");
96 setUri(url);
97 return send();
98}
HttpRequest & setUri(const std::string &uri)
Set the URI for the request.

References send(), setMethod(), and setUri().

+ Here is the call graph for this function:

◆ get() [1/2]

HttpResponse HttpRequest::get ( )
Parameters
urlThe URL to send the request to.
Returns
HttpResponse object containing the response.

Definition at line 46 of file HttpRequest.cpp.

47{
48 setMethod("GET");
49 return send();
50}

References send(), and setMethod().

Referenced by TimeManager::fetchAndApplyTimezoneFromOpenMeteo(), and TimeManager::getLocationFromIp().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ get() [2/2]

HttpResponse HttpRequest::get ( const std::string &  url)

Definition at line 52 of file HttpRequest.cpp.

53{
54 setMethod("GET");
55 setUri(url);
56 return send();
57}

References send(), setMethod(), and setUri().

+ Here is the call graph for this function:

◆ getBody()

const std::string & HttpRequest::getBody ( ) const
inline

Definition at line 232 of file HttpRequest.h.

233 {
234 return body;
235 }

References body.

Referenced by JsonRequestHelper::getFullJson(), HttpServer::handleClient(), MultipartParser::handleMultipart(), and json().

+ Here is the caller graph for this function:

◆ getBoundary()

const std::string HttpRequest::getBoundary ( ) const
inline
Returns
Boundary string or empty string if not present.

Definition at line 205 of file HttpRequest.h.

206 {
207 auto contentType = getContentType();
208 auto boundaryPos = contentType.find("boundary=");
209 if (boundaryPos != std::string::npos)
210 {
211 return contentType.substr(boundaryPos + 9);
212 }
213 return "";
214 }
const std::string getContentType() const
Get the raw Content-Type string.

References getContentType().

Referenced by HttpServer::handleClient().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ getContentLength()

int HttpRequest::getContentLength ( ) const
inline
Returns
Content length in bytes, or 0 if absent.

Definition at line 263 of file HttpRequest.h.

264 {
265 std::string content_length_str = getHeader("content-length");
266 int contentLength = 0;
267 if (!content_length_str.empty())
268 {
269 contentLength = std::stoi(content_length_str);
270 }
271 return contentLength;
272 }
std::string getHeader(const std::string &field) const
Get a specific header field (case-insensitive).

References getHeader().

Referenced by HttpServer::handleClient(), and receive().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ getContentType()

const std::string HttpRequest::getContentType ( ) const
inline

Definition at line 196 of file HttpRequest.h.

197 {
198 return getHeader("content-type");
199 }

References getHeader().

Referenced by getBoundary(), and HttpServer::handleClient().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ getCookie()

const std::string HttpRequest::getCookie ( const std::string &  name) const

Get a specific cookie by name.

Parameters
nameCookie name.
Returns
Cookie value or empty string.
Parameters
nameCookie name.
Returns
std::string Value of the cookie or empty string.

Definition at line 381 of file HttpRequest.cpp.

382{
383 auto cookies = getCookies();
384 auto it = cookies.find(name);
385 return (it != cookies.end()) ? it->second : "";
386}
const std::unordered_map< std::string, std::string > getCookies() const
Get all parsed cookies.

References getCookies().

+ Here is the call graph for this function:

◆ getCookies()

const std::unordered_map< std::string, std::string > HttpRequest::getCookies ( ) const

Extract and return all cookies from the Cookie header.

Returns
A map of cookie names to values.
std::unordered_map<std::string, std::string> Map of cookie name-value pairs.

Definition at line 354 of file HttpRequest.cpp.

355{
356 std::unordered_map<std::string, std::string> cookies;
357 std::string cookieHeader = getHeader("cookie");
358 std::istringstream stream(cookieHeader);
359 std::string pair;
360 while (std::getline(stream, pair, ';'))
361 {
362 size_t eq = pair.find('=');
363 if (eq != std::string::npos)
364 {
365 std::string key = pair.substr(0, eq);
366 std::string value = pair.substr(eq + 1);
367 key.erase(0, key.find_first_not_of(" \t"));
368 value.erase(0, value.find_first_not_of(" \t"));
369 cookies[key] = value;
370 }
371 }
372 return cookies;
373}

References getHeader().

Referenced by getCookie(), and HttpServer::handleClient().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ getFormParams()

const std::unordered_multimap< std::string, std::string > HttpRequest::getFormParams ( )

Parse the request body as form-urlencoded content.

Returns
Map of form parameters.

Definition at line 403 of file HttpRequest.cpp.

404{
405 return parseUrlEncoded(body);
406}
std::unordered_multimap< std::string, std::string > parseUrlEncoded(const std::string &data)
Definition url_utils.cpp:67

References body, and parseUrlEncoded().

Referenced by HttpServer::handleClient().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ getHeader()

std::string HttpRequest::getHeader ( const std::string &  field) const
inline
Parameters
fieldHeader field name.
Returns
The header value or empty string if not found.

Definition at line 114 of file HttpRequest.h.

115 {
116 auto it = headers.find(toLower(field));
117 return (it != headers.end()) ? it->second : "";
118 }
std::map< std::string, std::string > headers
std::string toLower(std::string str)
Definition utility.cpp:93

References headers, and toLower().

Referenced by Router::getAuthorizationToken(), getContentLength(), getContentType(), getCookies(), HttpServer::handleClient(), MultipartParser::handleMultipart(), isMultipart(), and FrameworkManager::warmUp().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ getHeaderEnd()

size_t HttpRequest::getHeaderEnd ( )
inline
Returns
Byte offset.

Definition at line 153 of file HttpRequest.h.

154 {
155 return headerEnd;
156 }
size_t headerEnd

References headerEnd.

Referenced by HttpServer::handleClient().

+ Here is the caller graph for this function:

◆ getHeaders()

const std::map< std::string, std::string > & HttpRequest::getHeaders ( ) const
inline
Returns
Map of header key-value pairs.

Definition at line 124 of file HttpRequest.h.

125 {
126 return headers;
127 }

References headers.

Referenced by HttpServer::handleClient(), and receive().

+ Here is the caller graph for this function:

◆ getHost()

const std::string & HttpRequest::getHost ( ) const
inline

Definition at line 161 of file HttpRequest.h.

162 {
163 return host;
164 }
std::string host

References host.

◆ getMethod()

const std::string & HttpRequest::getMethod ( ) const
inline

Definition at line 311 of file HttpRequest.h.

312 {
313 return method;
314 }

References method.

Referenced by HttpServer::handleClient(), and Router::handleRequest().

+ Here is the caller graph for this function:

◆ getMethodAndPath()

bool HttpRequest::getMethodAndPath ( const std::string &  rawHeaders,
std::string &  method,
std::string &  path 
)
static

Extract HTTP method and path from request line.

Parameters
bufferRaw request buffer.
methodOutput buffer for method.
pathOutput buffer for path.
Returns
True on success.
Parameters
bufferThe raw request buffer.
clientSocketThe client socket (not used, included for consistency).
methodOutput buffer for method.
pathOutput buffer for path.
Returns
true on success, false on failure.

Definition at line 174 of file HttpRequest.cpp.

175{
176 TRACE("Parsing request data: %s\n", rawHeaders.c_str());
177 std::istringstream stream(rawHeaders);
178 std::string requestLine;
179 if (!std::getline(stream, requestLine)) {
180 printf("Failed to read request line\n");
181 return false;
182 }
183
184 std::istringstream lineStream(requestLine);
185 if (!(lineStream >> method >> path)) {
186 printf("Error parsing HTTP request method and path\n");
187 return false;
188 }
189 return true;
190}

References method, path, and TRACE.

Referenced by receive().

+ Here is the caller graph for this function:

◆ getOutputFilePath()

std::string HttpRequest::getOutputFilePath ( ) const

Definition at line 530 of file HttpRequest.cpp.

530 {
531 return outputFilePath;
532}
std::string outputFilePath

References outputFilePath.

◆ getPath()

const std::string & HttpRequest::getPath ( ) const
inline

Definition at line 319 of file HttpRequest.h.

320 {
321 return path;
322 }

References path.

Referenced by HttpFileserver::handle_list_directory(), HttpFileserver::handle_static_request(), HttpServer::handleClient(), and Router::handleRequest().

+ Here is the caller graph for this function:

◆ getProtocol()

const std::string & HttpRequest::getProtocol ( ) const
inline

Definition at line 166 of file HttpRequest.h.

167 {
168 return protocol;
169 }
std::string protocol

References protocol.

◆ getQuery()

const std::string & HttpRequest::getQuery ( ) const
inline

Definition at line 335 of file HttpRequest.h.

336 {
337 return query;
338 }

References query.

Referenced by HttpServer::handleClient().

+ Here is the caller graph for this function:

◆ getQueryParams()

const std::unordered_multimap< std::string, std::string > HttpRequest::getQueryParams ( )

Parse the query string into a key-value map.

Returns
Map of query parameters.

Definition at line 393 of file HttpRequest.cpp.

394{
395 return parseUrlEncoded(query);
396}

References parseUrlEncoded(), and query.

Referenced by HttpServer::handleClient(), and GpioController::handleGetMultipleGpios().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ getRootCACertificate()

const std::string & HttpRequest::getRootCACertificate ( ) const
inline
Returns
const std::string& PEM-encoded root certificate.

Definition at line 444 of file HttpRequest.h.

445 {
446 return rootCACertificate;
447 }
std::string rootCACertificate

References rootCACertificate.

◆ getTcp()

Tcp * HttpRequest::getTcp ( ) const
inline

Definition at line 344 of file HttpRequest.h.

345 {
346 return tcp;
347 }

References tcp.

Referenced by MultipartParser::handleMultipart().

+ Here is the caller graph for this function:

◆ getUri()

const std::string & HttpRequest::getUri ( ) const
inline

Definition at line 327 of file HttpRequest.h.

328 {
329 return uri;
330 }

References uri.

Referenced by HttpServer::handleClient().

+ Here is the caller graph for this function:

◆ handle_multipart()

int HttpRequest::handle_multipart ( HttpResponse res)

Handle multipart/form-data content using MultipartParser.

Parameters
resReference to the response.
Returns
0 on success, -1 on failure.
Parameters
clientSocketThe client socket.
reqReference to this request.
Returns
int 0 on success, -1 on failure.

Definition at line 343 of file HttpRequest.cpp.

344{
345 MultipartParser parser;
346 return parser.handleMultipart(*this, res) ? 0 : -1;
347}
Parses and processes multipart/form-data uploads over HTTP.
bool handleMultipart(HttpRequest &req, HttpResponse &res)
Begin processing the multipart upload from the socket.

References MultipartParser::handleMultipart().

Referenced by DashboardController::uploadHandler().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ isBodyTruncated()

bool HttpRequest::isBodyTruncated ( ) const
inline

Definition at line 238 of file HttpRequest.h.

238{ return bodyTruncated; }
bool bodyTruncated

References bodyTruncated.

◆ isFormUrlEncoded()

bool HttpRequest::isFormUrlEncoded ( ) const
inline

Definition at line 178 of file HttpRequest.h.

179 {
180 auto it = headers.find("content-type");
181 return it != headers.end() && it->second.find("application/x-www-form-urlencoded") != std::string::npos;
182 }

References headers.

◆ isJson()

bool HttpRequest::isJson ( ) const
inline

Definition at line 187 of file HttpRequest.h.

188 {
189 auto it = headers.find("content-type");
190 return it != headers.end() && it->second.find("application/json") != std::string::npos;
191 }

References headers.

Referenced by JsonRequestHelper::getFullJson().

+ Here is the caller graph for this function:

◆ isMultipart()

bool HttpRequest::isMultipart ( ) const
inline

Definition at line 219 of file HttpRequest.h.

220 {
221 auto contentType = getHeader("content-type");
222 return contentType.find("multipart/form-data") != std::string::npos;
223 }

References getHeader().

Referenced by HttpServer::handleClient(), and receive().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ json()

nlohmann::json HttpRequest::json ( ) const
inline

Returns an empty object if parsing fails.

Returns
nlohmann::json Parsed JSON object or empty on failure.

Definition at line 281 of file HttpRequest.h.

282 {
283 return nlohmann::json::parse(getBody(), nullptr, false);
284 }
const std::string & getBody() const
Get the request body (copy).

References getBody().

Referenced by setJson().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ markBodyTruncated()

void HttpRequest::markBodyTruncated ( )
inline

Definition at line 239 of file HttpRequest.h.

239{ bodyTruncated = true; }

References bodyTruncated.

Referenced by appendRemainingBody().

+ Here is the caller graph for this function:

◆ parseHeaders()

void HttpRequest::parseHeaders ( const char *  raw)
private

Definition at line 160 of file HttpRequest.cpp.

161{
163}
static std::map< std::string, std::string > parseHeaders(const std::string &rawHeaders)
Parses the HTTP headers from a raw header string.

References headers, and HttpParser::parseHeaders().

Referenced by HttpRequest(), and HttpRequest().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ post() [1/2]

HttpResponse HttpRequest::post ( )

Definition at line 59 of file HttpRequest.cpp.

60{
61 setMethod("POST");
62 return send();
63}

References send(), and setMethod().

+ Here is the call graph for this function:

◆ post() [2/2]

HttpResponse HttpRequest::post ( const std::string &  url,
const std::string &  body 
)

Definition at line 77 of file HttpRequest.cpp.

78{
79 setMethod("POST");
80 setUri(url);
82 return send();
83}
HttpRequest & setBody(const std::string &body)
Set the body of the request.

References body, send(), setBody(), setMethod(), and setUri().

+ Here is the call graph for this function:

◆ printHeaders()

void HttpRequest::printHeaders ( ) const
inline

Definition at line 132 of file HttpRequest.h.

133 {
134 for (const auto &header : headers)
135 {
136 std::cout << header.first << ": " << header.second << std::endl;
137 }
138 }

References headers.

◆ put() [1/2]

HttpResponse HttpRequest::put ( )

Definition at line 65 of file HttpRequest.cpp.

66{
67 setMethod("PUT");
68 return send();
69}

References send(), and setMethod().

+ Here is the call graph for this function:

◆ put() [2/2]

HttpResponse HttpRequest::put ( const std::string &  url,
const std::string &  body 
)

Definition at line 85 of file HttpRequest.cpp.

86{
87 setMethod("PUT");
88 setUri(url);
90 return send();
91}

References body, send(), setBody(), setMethod(), and setUri().

+ Here is the call graph for this function:

◆ receive()

HttpRequest HttpRequest::receive ( Tcp tcp)
static

Receive raw bytes from the client socket into a buffer.

Parameters
Instanceof tcp
Returns
A fully populated HttpRequest object.
Parameters
Tcp*The TCP connection to read from.
Returns
HttpRequest Parsed HttpRequest object containing method, path, headers, and body.
Note
This function reads the request line, headers, and body from the TCP socket. It handles both multipart and non-multipart requests, parsing headers and body accordingly.

Definition at line 266 of file HttpRequest.cpp.

267{
268 TRACE("Receiving request on socket %d\n", tcp->getSocketFd());
269
270 char buffer[BUFFER_SIZE]; // Declare buffer size
271 std::string body = ""; // Initialize empty body
272 std::map<std::string, std::string> headers; // Initialize empty headers
273 std::string method = {0}; // Initialize method buffer
274 std::string path = {0}; // Initialize path buffer
275
276 auto result = receiveUntilHeadersComplete(tcp);
277 if (!result) {
278 return HttpRequest("", "", "");
279 }
280
281 const auto& [rawHeaders, initialBody] = *result;
282
283 if (!getMethodAndPath(rawHeaders, method, path)) {
284 return HttpRequest("", "", "");
285 }
286
287 // Create the request which will parse the headers
288 TRACE("Raw headers: %s\n", rawHeaders.c_str());
289
290 HttpRequest request(tcp, rawHeaders, std::string(method), std::string(path));
291 request.setBody(initialBody); // Set the initial body if any
292
293 // NOW split path and query
294 std::string cleanPath = path;
295 std::string queryString = "";
296
297 size_t qpos = cleanPath.find('?');
298 if (qpos != std::string::npos)
299 {
300 queryString = cleanPath.substr(qpos + 1);
301 cleanPath = cleanPath.substr(0, qpos);
302 }
303 request.setPath(cleanPath); // Set the cleaned path as the URI
304 request.setQueryString(queryString); // Set the query string
305
306 // Get headers from the HttpRequest object
307 headers = request.getHeaders();
308
309 TRACE("Parsed headers:\n");
310 for (const auto &header : headers)
311 {
312 TRACE("%s: %s\n", header.first.c_str(), header.second.c_str());
313 }
314
315 int contentLength = request.getContentLength();
316 TRACE("Content-Length: %d\n", contentLength);
317
318 if (contentLength > 0)
319 {
320 TRACE("Content-Length is greater than 0\n");
321 if (request.isMultipart())
322 {
323 TRACE("Multipart request detected\n");
324 return request;
325 }
326
327 TRACE("Non-multipart request detected\n");
328
329 request.appendRemainingBody(contentLength);
330 TRACE("Final body length: %zu\n", body.length());
331 TRACE("HttpRequest object constructed\n");
332 }
333 return request;
334}
#define BUFFER_SIZE
Forward declaration for potential routing needs.
Definition HttpRequest.h:32
static bool getMethodAndPath(const std::string &data, std::string &method, std::string &path)
Parse the HTTP method and path from the first request line.
static std::optional< std::pair< std::string, std::string > > receiveUntilHeadersComplete(Tcp *conn)
int getSocketFd() const
Get the raw socket file descriptor (may be -1 for TLS-only connection).
Definition Tcp.h:124

References appendRemainingBody(), body, BUFFER_SIZE, getContentLength(), getHeaders(), getMethodAndPath(), Tcp::getSocketFd(), headers, HttpRequest(), isMultipart(), method, path, receiveUntilHeadersComplete(), setBody(), setPath(), setQueryString(), tcp, and TRACE.

Referenced by HttpServer::handleClient().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ receiveUntilHeadersComplete()

std::optional< std::pair< std::string, std::string > > HttpRequest::receiveUntilHeadersComplete ( Tcp conn)
static

Definition at line 194 of file HttpRequest.cpp.

194 {
195 std::string requestText;
196 char buffer[HTTP_BUFFER_SIZE];
197
198 while (true) {
199 int received = conn->recv(buffer, sizeof(buffer), HTTP_RECEIVE_TIMEOUT);
200 if (received <= 0) {
201 printf("[HttpRequest] Failed to receive header - usually Safari reusing socket it shouldn't\n");
202 return std::nullopt;
203 }
204
205 requestText.append(buffer, received);
206
207 size_t headerEnd = requestText.find("\r\n\r\n");
208 if (headerEnd != std::string::npos) {
209 size_t bodyStart = headerEnd + 4;
210 std::string headers = requestText.substr(0, headerEnd);
211 std::string leftover = (bodyStart < requestText.size())
212 ? requestText.substr(bodyStart)
213 : "";
214 return std::make_pair(std::move(headers), std::move(leftover));
215 }
216
217 if (requestText.size() > MAX_HEADER_BYTES) {
218 printf("[HttpRequest] Headers exceeded %zu bytes, rejecting\n", MAX_HEADER_BYTES);
219 return std::nullopt;
220 }
221 }
222}
constexpr size_t MAX_HEADER_BYTES

References headerEnd, headers, HTTP_BUFFER_SIZE, HTTP_RECEIVE_TIMEOUT, MAX_HEADER_BYTES, and Tcp::recv().

Referenced by receive().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ send()

HttpResponse HttpRequest::send ( )
Returns
HttpResponse object containing the response.

Definition at line 100 of file HttpRequest.cpp.

101{
102#ifdef PICO_HTTP_ENABLE_HTTP_CLIENT
103 HttpResponse response;
104 HttpClient client;
105 client.sendRequest(*this, response);
106 return response;
107#else
108 // If HTTP client is not enabled, return an empty response
109 return HttpResponse(nullptr);
110#endif
111}
Represents an HTTP response object.

Referenced by del(), del(), get(), get(), post(), post(), put(), and put().

+ Here is the caller graph for this function:

◆ setAcceptEncoding()

HttpRequest & HttpRequest::setAcceptEncoding ( const std::string &  encoding)

Definition at line 485 of file HttpRequest.cpp.

486{
487 headers["Accept-Encoding"] = encoding;
488 return *this;
489}

References headers.

◆ setBody()

HttpRequest & HttpRequest::setBody ( const std::string &  body)
Parameters
aBodyThe full request body content.

Definition at line 140 of file HttpRequest.cpp.

141{
142 body = b;
143 return *this;
144}

References body.

Referenced by post(), put(), and receive().

+ Here is the caller graph for this function:

◆ setHeader()

HttpRequest & HttpRequest::setHeader ( const std::string &  key,
const std::string &  value 
)

Definition at line 473 of file HttpRequest.cpp.

474{
475 headers[key] = value;
476 return *this;
477}

References headers.

Referenced by setJson(), setJson(), and FrameworkManager::warmUp().

+ Here is the caller graph for this function:

◆ setHeaderEnd()

void HttpRequest::setHeaderEnd ( size_t  end)
inline
Parameters
endOffset into the raw request.

Definition at line 144 of file HttpRequest.h.

145 {
146 headerEnd = end;
147 }

References headerEnd.

◆ setHeaders()

HttpRequest & HttpRequest::setHeaders ( const std::map< std::string, std::string > &  headers)

Definition at line 464 of file HttpRequest.cpp.

465{
466 for (const auto &[k, v] : headers)
467 {
468 this->headers[k] = v;
469 }
470 return *this;
471}

References headers.

◆ setHost()

HttpRequest & HttpRequest::setHost ( const std::string &  host)

Definition at line 452 of file HttpRequest.cpp.

453{
454 host = h;
455 return *this;
456}

References host.

◆ setJson() [1/2]

HttpRequest & HttpRequest::setJson ( const nlohmann::json &  json)
Parameters
jsonJSON object to set as body.

Definition at line 153 of file HttpRequest.cpp.

154{
155 setHeader("Content-Type", "application/json");
156 body = json.dump();
157 return *this;
158}
nlohmann::json json
HttpRequest & setHeader(const std::string &key, const std::string &value)

References body, and setHeader().

+ Here is the call graph for this function:

◆ setJson() [2/2]

HttpRequest & HttpRequest::setJson ( const std::string &  json)
Parameters
jsonJSON string to set as body.

Definition at line 146 of file HttpRequest.cpp.

147{
148 setHeader("Content-Type", "application/json");
149 body = json;
150 return *this;
151}
nlohmann::json json() const
Safely parse the request body as JSON (non-throwing).

References body, json(), and setHeader().

+ Here is the call graph for this function:

◆ setMethod()

HttpRequest & HttpRequest::setMethod ( const std::string &  method)
inline

Definition at line 293 of file HttpRequest.h.

294 {
295 this->method = method;
296 return *this;
297 }

References method.

Referenced by del(), del(), get(), get(), post(), post(), put(), put(), and FrameworkManager::warmUp().

+ Here is the caller graph for this function:

◆ setPath()

HttpRequest & HttpRequest::setPath ( const std::string &  path)
inline

Definition at line 302 of file HttpRequest.h.

303 {
304 this->path = path;
305 return *this;
306 }

References path.

Referenced by receive(), and FrameworkManager::warmUp().

+ Here is the caller graph for this function:

◆ setProtocol()

HttpRequest & HttpRequest::setProtocol ( const std::string &  protocol)

Definition at line 458 of file HttpRequest.cpp.

459{
460 protocol = p;
461 return *this;
462}

References protocol.

◆ setQueryString()

void HttpRequest::setQueryString ( const std::string &  query)
inlineprivate

Definition at line 457 of file HttpRequest.h.

458 {
459 this->query = query;
460 }

References query.

Referenced by receive().

+ Here is the caller graph for this function:

◆ setRootCACertificate()

HttpRequest & HttpRequest::setRootCACertificate ( const std::string &  certData)
Parameters
certDataPEM-encoded certificate.

Definition at line 490 of file HttpRequest.cpp.

491{
492 rootCACertificate = certData;
493 return *this;
494}

References rootCACertificate.

◆ setUri()

HttpRequest & HttpRequest::setUri ( const std::string &  uri)

Parses the uri into protocol, host, and path. But not if it is just a /path

Parameters
uriThe URI to set.
Returns
Reference to this request.

Definition at line 423 of file HttpRequest.cpp.

424{
425 const auto proto_end = uri.find("://");
426 if (proto_end == std::string::npos)
427 {
428 // Relative URI — just set it, do not overwrite protocol or host
429 this->uri = uri;
430 return *this;
431 }
432
433 // Full URL — parse into protocol, host, and path
434 protocol = uri.substr(0, proto_end);
435 std::string rest = uri.substr(proto_end + 3); // skip "://"
436
437 const auto path_start = rest.find('/');
438 if (path_start == std::string::npos)
439 {
440 host = rest;
441 this->uri = "/";
442 }
443 else
444 {
445 host = rest.substr(0, path_start);
446 this->uri = rest.substr(path_start);
447 }
448
449 return *this;
450}

References host, protocol, and uri.

Referenced by del(), get(), post(), and put().

+ Here is the caller graph for this function:

◆ setUserAgent()

HttpRequest & HttpRequest::setUserAgent ( const std::string &  userAgent)

Definition at line 479 of file HttpRequest.cpp.

480{
481 headers["User-Agent"] = userAgent;
482 return *this;
483}

References headers.

◆ toFile()

HttpRequest & HttpRequest::toFile ( const std::string &  path)

Definition at line 521 of file HttpRequest.cpp.

521 {
522 this->outputFilePath = path;
523 return *this;
524}

References outputFilePath, and path.

◆ wantsToFile()

bool HttpRequest::wantsToFile ( ) const

Definition at line 526 of file HttpRequest.cpp.

526 {
527 return !outputFilePath.empty();
528}

References outputFilePath.

Member Data Documentation

◆ body

std::string HttpRequest::body
private

◆ bodyTruncated

bool HttpRequest::bodyTruncated = false
private

Definition at line 475 of file HttpRequest.h.

Referenced by isBodyTruncated(), and markBodyTruncated().

◆ clientIp

std::string HttpRequest::clientIp
private

Definition at line 464 of file HttpRequest.h.

◆ headerEnd

size_t HttpRequest::headerEnd = 0
private

Definition at line 474 of file HttpRequest.h.

Referenced by getHeaderEnd(), receiveUntilHeadersComplete(), and setHeaderEnd().

◆ headers

std::map<std::string, std::string> HttpRequest::headers
private

◆ host

std::string HttpRequest::host
private

Definition at line 469 of file HttpRequest.h.

Referenced by getHost(), setHost(), and setUri().

◆ method

std::string HttpRequest::method
private

Definition at line 465 of file HttpRequest.h.

Referenced by getMethod(), getMethodAndPath(), receive(), and setMethod().

◆ outputFilePath

std::string HttpRequest::outputFilePath
private

Definition at line 476 of file HttpRequest.h.

Referenced by getOutputFilePath(), toFile(), and wantsToFile().

◆ path

std::string HttpRequest::path
private

Definition at line 467 of file HttpRequest.h.

Referenced by getMethodAndPath(), getPath(), HttpRequest(), receive(), setPath(), and toFile().

◆ protocol

std::string HttpRequest::protocol
private

Definition at line 470 of file HttpRequest.h.

Referenced by getProtocol(), setProtocol(), and setUri().

◆ query

std::string HttpRequest::query
private

Definition at line 468 of file HttpRequest.h.

Referenced by getQuery(), getQueryParams(), HttpRequest(), and setQueryString().

◆ rootCACertificate

std::string HttpRequest::rootCACertificate
private

Definition at line 473 of file HttpRequest.h.

Referenced by getRootCACertificate(), and setRootCACertificate().

◆ tcp

Tcp* HttpRequest::tcp = nullptr
private

Definition at line 462 of file HttpRequest.h.

Referenced by appendRemainingBody(), getTcp(), and receive().

◆ uri

std::string HttpRequest::uri
private

Definition at line 466 of file HttpRequest.h.

Referenced by getUri(), HttpRequest(), and setUri().


The documentation for this class was generated from the following files: