Hi everyone,
I'm sending POST
and GET
http requests to a server via maxon::Url
and maxon::FileUtilities::ReadFileToMemory(serverURL, charArray)
.
The charArray
will be sucessfully filled with the response body if the server responds with a status code 200 (OK)
after the request has been sent with ReadFileToMemory(serverURL, charArray)
. If the server responds with an error code like 401 (Unauthorized)
the ReadFileToMemory()
function unfortunately also returns an error, even if the client / server - communication was successfull. The main problem is that the response body (charArray
) will be empty in such a case, even if the response header ("content-length
") shows that a response body with a specific size was sent. I need to process the content of the response body if the server responds with a status code other than 200 (OK)
after a POST
request, which is a common approach in web development.
Is the response body empty by design in such a case, or is this a bug?
I prepared a small example which sends a GET
request to the service https://httpstat.us.
A request like https://httpstat.us/401 will respond with the body "401 Unauthorized"
which will also be reflected in the response header:"Content-Length: 16"
.
This can be observed with a tool like Postman (https://www.postman.com/downloads/), but the example code below will unfortunately result in an empty response body.
Any ideas how I can get access to the response body? Thanks in advance!
Best regards,
Tim
#include "maxon/network_url.h"
#include "maxon/network_ip_ssl.h"
#include "maxon/network_ip.h"
#include "maxon/file_utilities.h"
static maxon::Result<void> ProducesAnEmptyResponseBody()
{
maxon::Url serverURL{ String("https://httpstat.us/401") };
// Set the request headers
maxon::DataDictionary requestHeaders;
requestHeaders.Set(maxon::Data(String("Content-Type")), maxon::Data(String("application/json"))) iferr_ignore();
iferr (serverURL.Set(maxon::URLFLAGS::HTTP_ADDITIONAL_REQUEST_HEADER, requestHeaders))
{
ApplicationOutput("Error 1: @", err);
return err;
}
// Setup a dictionary for the response headers
maxon::DataDictionary responseHeaders;
iferr (serverURL.Set(maxon::URLFLAGS::HTTP_RESPONSE_HEADER, &responseHeaders))
{
ApplicationOutput("Error 2: @", err);
return err;
}
// Sends the request and retrieves the response in a memory buffer.
// The response body will be stored in a char array.
// The response headers (includes the http status code)
// will be stored in the previously set response header dictionary.
maxon::BaseArray<maxon::Char> charArray;
iferr (maxon::FileUtilities::ReadFileToMemory(serverURL, charArray))
{
ApplicationOutput("Error 3: @", err);
}
// Store the response body as a string.
String responseBody = maxon::String(charArray);
ApplicationOutput("responseBody = '@'", responseBody);
// Extract the status code from the response header, etc...
// ApplicationOutput("responseHeaders = '@'", responseHeaders);
return maxon::OK;
}