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.
 
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 210 of file HttpRequest.cpp.

210 {
211 size_t remaining = expectedLength - body.size();
212 char buffer[HTTP_BUFFER_SIZE];
213
214 while (remaining > 0) {
215 size_t toRead = std::min(remaining, sizeof(buffer));
216 int received = tcp->recv(buffer, toRead, HTTP_RECEIVE_TIMEOUT);
217 if (received <= 0) {
218 printf("Error receiving body chunk\n");
219 return false;
220 }
221 size_t currentSize = body.size();
222 if (currentSize >= MAX_HTTP_BODY_LENGTH) {
223 TRACE("Body exceeds max length. Truncating.\n");
225 break;
226 }
227 size_t allowed = MAX_HTTP_BODY_LENGTH - currentSize;
228 size_t toAppend = std::min(static_cast<size_t>(received), allowed);
229 body.append(buffer, toAppend);
230
231 if (toAppend < static_cast<size_t>(received)) {
232 TRACE("Body chunk truncated due to size limit.\n");
234 break;
235 }
236 remaining -= received;
237 }
238 return true;
239}
#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 398 of file HttpRequest.cpp.

399{
400 return HttpRequest("", "", "");
401}
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 251 of file HttpRequest.h.

252 {
253 std::string content_length_str = getHeader("content-length");
254 int contentLength = 0;
255 if (!content_length_str.empty())
256 {
257 contentLength = std::stoi(content_length_str);
258 }
259 return contentLength;
260 }
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 367 of file HttpRequest.cpp.

368{
369 auto cookies = getCookies();
370 auto it = cookies.find(name);
371 return (it != cookies.end()) ? it->second : "";
372}
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 340 of file HttpRequest.cpp.

341{
342 std::unordered_map<std::string, std::string> cookies;
343 std::string cookieHeader = getHeader("cookie");
344 std::istringstream stream(cookieHeader);
345 std::string pair;
346 while (std::getline(stream, pair, ';'))
347 {
348 size_t eq = pair.find('=');
349 if (eq != std::string::npos)
350 {
351 std::string key = pair.substr(0, eq);
352 std::string value = pair.substr(eq + 1);
353 key.erase(0, key.find_first_not_of(" \t"));
354 value.erase(0, value.find_first_not_of(" \t"));
355 cookies[key] = value;
356 }
357 }
358 return cookies;
359}

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 389 of file HttpRequest.cpp.

390{
391 return parseUrlEncoded(body);
392}
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 299 of file HttpRequest.h.

300 {
301 return method;
302 }

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 160 of file HttpRequest.cpp.

161{
162 TRACE("Parsing request data: %s\n", rawHeaders.c_str());
163 std::istringstream stream(rawHeaders);
164 std::string requestLine;
165 if (!std::getline(stream, requestLine)) {
166 printf("Failed to read request line\n");
167 return false;
168 }
169
170 std::istringstream lineStream(requestLine);
171 if (!(lineStream >> method >> path)) {
172 printf("Error parsing HTTP request method and path\n");
173 return false;
174 }
175 return true;
176}

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 516 of file HttpRequest.cpp.

516 {
517 return outputFilePath;
518}
std::string outputFilePath

References outputFilePath.

◆ getPath()

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

Definition at line 307 of file HttpRequest.h.

308 {
309 return path;
310 }

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 323 of file HttpRequest.h.

324 {
325 return query;
326 }

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 379 of file HttpRequest.cpp.

380{
381 return parseUrlEncoded(query);
382}

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 432 of file HttpRequest.h.

433 {
434 return rootCACertificate;
435 }
std::string rootCACertificate

References rootCACertificate.

◆ getTcp()

Tcp * HttpRequest::getTcp ( ) const
inline

Definition at line 332 of file HttpRequest.h.

333 {
334 return tcp;
335 }

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 315 of file HttpRequest.h.

316 {
317 return uri;
318 }

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 329 of file HttpRequest.cpp.

330{
331 MultipartParser parser;
332 return parser.handleMultipart(*this, res) ? 0 : -1;
333}
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 269 of file HttpRequest.h.

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

References getBody().

+ Here is the call 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 146 of file HttpRequest.cpp.

147{
149}
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 252 of file HttpRequest.cpp.

253{
254 TRACE("Receiving request on socket %d\n", tcp->getSocketFd());
255
256 char buffer[BUFFER_SIZE]; // Declare buffer size
257 std::string body = ""; // Initialize empty body
258 std::map<std::string, std::string> headers; // Initialize empty headers
259 std::string method = {0}; // Initialize method buffer
260 std::string path = {0}; // Initialize path buffer
261
262 auto result = receiveUntilHeadersComplete(tcp);
263 if (!result) {
264 return HttpRequest("", "", "");
265 }
266
267 const auto& [rawHeaders, initialBody] = *result;
268
269 if (!getMethodAndPath(rawHeaders, method, path)) {
270 return HttpRequest("", "", "");
271 }
272
273 // Create the request which will parse the headers
274 TRACE("Raw headers: %s\n", rawHeaders.c_str());
275
276 HttpRequest request(tcp, rawHeaders, std::string(method), std::string(path));
277 request.setBody(initialBody); // Set the initial body if any
278
279 // NOW split path and query
280 std::string cleanPath = path;
281 std::string queryString = "";
282
283 size_t qpos = cleanPath.find('?');
284 if (qpos != std::string::npos)
285 {
286 queryString = cleanPath.substr(qpos + 1);
287 cleanPath = cleanPath.substr(0, qpos);
288 }
289 request.setPath(cleanPath); // Set the cleaned path as the URI
290 request.setQueryString(queryString); // Set the query string
291
292 // Get headers from the HttpRequest object
293 headers = request.getHeaders();
294
295 TRACE("Parsed headers:\n");
296 for (const auto &header : headers)
297 {
298 TRACE("%s: %s\n", header.first.c_str(), header.second.c_str());
299 }
300
301 int contentLength = request.getContentLength();
302 TRACE("Content-Length: %d\n", contentLength);
303
304 if (contentLength > 0)
305 {
306 TRACE("Content-Length is greater than 0\n");
307 if (request.isMultipart())
308 {
309 TRACE("Multipart request detected\n");
310 return request;
311 }
312
313 TRACE("Non-multipart request detected\n");
314
315 request.appendRemainingBody(contentLength);
316 TRACE("Final body length: %zu\n", body.length());
317 TRACE("HttpRequest object constructed\n");
318 }
319 return request;
320}
#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 180 of file HttpRequest.cpp.

180 {
181 std::string requestText;
182 char buffer[HTTP_BUFFER_SIZE];
183
184 while (true) {
185 int received = conn->recv(buffer, sizeof(buffer), HTTP_RECEIVE_TIMEOUT);
186 if (received <= 0) {
187 printf("[HttpRequest] Failed to receive header - usually Safari reusing socket it shouldn't\n");
188 return std::nullopt;
189 }
190
191 requestText.append(buffer, received);
192
193 size_t headerEnd = requestText.find("\r\n\r\n");
194 if (headerEnd != std::string::npos) {
195 size_t bodyStart = headerEnd + 4;
196 std::string headers = requestText.substr(0, headerEnd);
197 std::string leftover = (bodyStart < requestText.size())
198 ? requestText.substr(bodyStart)
199 : "";
200 return std::make_pair(std::move(headers), std::move(leftover));
201 }
202
203 if (requestText.size() > MAX_HEADER_BYTES) {
204 printf("[HttpRequest] Headers exceeded %zu bytes, rejecting\n", MAX_HEADER_BYTES);
205 return std::nullopt;
206 }
207 }
208}
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 471 of file HttpRequest.cpp.

472{
473 headers["Accept-Encoding"] = encoding;
474 return *this;
475}

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 459 of file HttpRequest.cpp.

460{
461 headers[key] = value;
462 return *this;
463}

References headers.

Referenced by 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 450 of file HttpRequest.cpp.

451{
452 for (const auto &[k, v] : headers)
453 {
454 this->headers[k] = v;
455 }
456 return *this;
457}

References headers.

◆ setHost()

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

Definition at line 438 of file HttpRequest.cpp.

439{
440 host = h;
441 return *this;
442}

References host.

◆ setMethod()

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

Definition at line 281 of file HttpRequest.h.

282 {
283 this->method = method;
284 return *this;
285 }

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 290 of file HttpRequest.h.

291 {
292 this->path = path;
293 return *this;
294 }

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 444 of file HttpRequest.cpp.

445{
446 protocol = p;
447 return *this;
448}

References protocol.

◆ setQueryString()

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

Definition at line 445 of file HttpRequest.h.

446 {
447 this->query = query;
448 }

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 476 of file HttpRequest.cpp.

477{
478 rootCACertificate = certData;
479 return *this;
480}

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 409 of file HttpRequest.cpp.

410{
411 const auto proto_end = uri.find("://");
412 if (proto_end == std::string::npos)
413 {
414 // Relative URI — just set it, do not overwrite protocol or host
415 this->uri = uri;
416 return *this;
417 }
418
419 // Full URL — parse into protocol, host, and path
420 protocol = uri.substr(0, proto_end);
421 std::string rest = uri.substr(proto_end + 3); // skip "://"
422
423 const auto path_start = rest.find('/');
424 if (path_start == std::string::npos)
425 {
426 host = rest;
427 this->uri = "/";
428 }
429 else
430 {
431 host = rest.substr(0, path_start);
432 this->uri = rest.substr(path_start);
433 }
434
435 return *this;
436}

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 465 of file HttpRequest.cpp.

466{
467 headers["User-Agent"] = userAgent;
468 return *this;
469}

References headers.

◆ toFile()

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

Definition at line 507 of file HttpRequest.cpp.

507 {
508 this->outputFilePath = path;
509 return *this;
510}

References outputFilePath, and path.

◆ wantsToFile()

bool HttpRequest::wantsToFile ( ) const

Definition at line 512 of file HttpRequest.cpp.

512 {
513 return !outputFilePath.empty();
514}

References outputFilePath.

Member Data Documentation

◆ body

std::string HttpRequest::body
private

Definition at line 460 of file HttpRequest.h.

Referenced by appendRemainingBody(), getBody(), getFormParams(), post(), put(), receive(), and setBody().

◆ bodyTruncated

bool HttpRequest::bodyTruncated = false
private

Definition at line 463 of file HttpRequest.h.

Referenced by isBodyTruncated(), and markBodyTruncated().

◆ clientIp

std::string HttpRequest::clientIp
private

Definition at line 452 of file HttpRequest.h.

◆ headerEnd

size_t HttpRequest::headerEnd = 0
private

Definition at line 462 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 457 of file HttpRequest.h.

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

◆ method

std::string HttpRequest::method
private

Definition at line 453 of file HttpRequest.h.

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

◆ outputFilePath

std::string HttpRequest::outputFilePath
private

Definition at line 464 of file HttpRequest.h.

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

◆ path

std::string HttpRequest::path
private

Definition at line 455 of file HttpRequest.h.

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

◆ protocol

std::string HttpRequest::protocol
private

Definition at line 458 of file HttpRequest.h.

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

◆ query

std::string HttpRequest::query
private

Definition at line 456 of file HttpRequest.h.

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

◆ rootCACertificate

std::string HttpRequest::rootCACertificate
private

Definition at line 461 of file HttpRequest.h.

Referenced by getRootCACertificate(), and setRootCACertificate().

◆ tcp

Tcp* HttpRequest::tcp = nullptr
private

Definition at line 450 of file HttpRequest.h.

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

◆ uri

std::string HttpRequest::uri
private

Definition at line 454 of file HttpRequest.h.

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


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