Skip to content

Commit

Permalink
ESP8266HTTPClient: allow getString() more than once (esp8266#5091)
Browse files Browse the repository at this point in the history
  • Loading branch information
yoursunny authored and d-a-v committed Sep 9, 2018
1 parent e93e9f6 commit fc96312
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 9 deletions.
31 changes: 23 additions & 8 deletions libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
class TransportTraits
{
public:
virtual ~TransportTraits()
virtual ~TransportTraits()
{
}

Expand Down Expand Up @@ -126,6 +126,7 @@ void HTTPClient::clear()
_returnCode = 0;
_size = -1;
_headers = "";
_payload.reset();
}


Expand Down Expand Up @@ -281,6 +282,16 @@ bool HTTPClient::begin(String host, uint16_t port, String uri, const uint8_t htt
* called after the payload is handled
*/
void HTTPClient::end(void)
{
disconnect();
clear();
}

/**
* disconnect
* close the TCP socket
*/
void HTTPClient::disconnect()
{
if(connected()) {
if(_tcp->available() > 0) {
Expand Down Expand Up @@ -734,28 +745,32 @@ int HTTPClient::writeToStream(Stream * stream)
return returnError(HTTPC_ERROR_ENCODING);
}

end();
disconnect();
return ret;
}

/**
* return all payload as String (may need lot of ram or trigger out of memory!)
* @return String
*/
String HTTPClient::getString(void)
const String& HTTPClient::getString(void)
{
StreamString sstring;
if (_payload) {
return *_payload;
}

_payload.reset(new StreamString());

if(_size) {
// try to reserve needed memmory
if(!sstring.reserve((_size + 1))) {
if(!_payload->reserve((_size + 1))) {
DEBUG_HTTPCLIENT("[HTTP-Client][getString] not enough memory to reserve a string! need: %d\n", (_size + 1));
return "";
return *_payload;
}
}

writeToStream(&sstring);
return sstring;
writeToStream(_payload.get());
return *_payload;
}

/**
Expand Down
6 changes: 5 additions & 1 deletion libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.h
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,8 @@ typedef enum {
class TransportTraits;
typedef std::unique_ptr<TransportTraits> TransportTraitsPtr;

class StreamString;

class HTTPClient
{
public:
Expand Down Expand Up @@ -185,7 +187,7 @@ class HTTPClient
WiFiClient& getStream(void);
WiFiClient* getStreamPtr(void);
int writeToStream(Stream* stream);
String getString(void);
const String& getString(void);

static String errorToString(int error);

Expand All @@ -196,6 +198,7 @@ class HTTPClient
};

bool beginInternal(String url, const char* expectedProtocol);
void disconnect();
void clear();
int returnError(int error);
bool connect(void);
Expand Down Expand Up @@ -228,6 +231,7 @@ class HTTPClient
int _size = -1;
bool _canReuse = false;
transferEncoding_t _transferEncoding = HTTPC_TE_IDENTITY;
std::unique_ptr<StreamString> _payload;
};


Expand Down

0 comments on commit fc96312

Please sign in to comment.