1
0
mirror of https://github.com/arduino-libraries/ArduinoHttpClient.git synced 2025-04-19 21:22:15 +03:00

Make HttpClient::responseBody more robust

Return invalidated String if memory allocation fails or content length
does not match body data length. Also, use timed reads to support
responses without a content length.
This commit is contained in:
Sandeep Mistry 2016-07-12 17:23:48 -04:00
parent dbf13c8aa7
commit fe46191445

View File

@ -32,7 +32,7 @@ void HttpClient::resetState()
{ {
iState = eIdle; iState = eIdle;
iStatusCode = 0; iStatusCode = 0;
iContentLength = 0; iContentLength = kNoContentLengthHeader;
iBodyLengthConsumed = 0; iBodyLengthConsumed = 0;
iContentLengthPtr = kContentLengthPrefix; iContentLengthPtr = kContentLengthPrefix;
iHttpResponseTimeout = kHttpResponseTimeout; iHttpResponseTimeout = kHttpResponseTimeout;
@ -521,12 +521,35 @@ String HttpClient::responseBody()
if (bodyLength > 0) if (bodyLength > 0)
{ {
response.reserve(bodyLength); // try to reserve bodyLength bytes
if (response.reserve(bodyLength) == 0) {
// String reserve failed
return String((const char*)NULL);
}
} }
while (available()) // keep on timedRead'ing, until:
// - we have a content length: body length equals consumed or no bytes
// available
// - no content length: no bytes are available
while (iBodyLengthConsumed != bodyLength)
{ {
response += (char)read(); int c = timedRead();
if (c == -1) {
// read timed out, done
break;
}
if (!response.concat((char)c)) {
// adding char failed
return String((const char*)NULL);
}
}
if (bodyLength > 0 && (unsigned int)bodyLength != response.length()) {
// failure, we did not read in reponse content length bytes
return String((const char*)NULL);
} }
return response; return response;