Send headers in Post request and read response text


#1

Hi,

I'm trying to interact with a web API through http request. I need to login, get the cookies and then send Post commands with specific data, then the API will respond with a text message. I have done this in other languages and I know it works fine.

In order to get a valid response from the API I need to pass the post data and the correct headers (Referer and Cookie at least), but I can't find a way to send both in a single call and still read the response text.

If I use readEntireTextStream() I can send the post data and read the response text, but I can't set extra headers. If I use createInputStream() I can send the correct headers and post data, but I can't read the response text as it returns an InputStream and doesn't have a parameter to hold the response. I see it has the option to set a Callback function but I can't find anything that would return the response.

So I'm very confused. How can I send the headers and read the response text?

Thanks in advance.


#2

I believe there's no way to accomplish that at the moment, so I decided to modify the readEntireTextStream method myself. Since it uses createInputStream I simply added the extra parameters I needed.

String URL::readEntireTextStream (const bool usePostCommand,
                                  String extraHeaders,
                                  StringPairArray* const responseHeaders) const
{
    const ScopedPointer<InputStream> in (createInputStream (usePostCommand, 0, 0,
                                                            extraHeaders, 0, responseHeaders));
    if (in != nullptr)
        return in->readEntireStreamAsString();
    return String::empty;
}

#3

I don't think you need to modify anything for this.  Just call createInputStream() with your parameters, then call readEntireStreamAsString() on that stream to get the results as a string.  Unless I'm missing something?


#4

Thanks for the reply, CowTipper! You are right, that method works the way I need. Really missed that one.

Thank you.