Overview
Features
Download
Documentation
Community
Add-Ons & Services

HTTPRequest, JSON & Content-Length

Please post support and help requests here.

HTTPRequest, JSON & Content-Length

Postby bquenin » 26 Jan 2013, 13:56

Hi,

I have a question about performing a HTTP POST request with a JSON body. I use the following code which works like a charm:

Code: Select all
    // Request
    JSON::Object jsonRequest;
    jsonRequest.set("firstName", firstName);
    jsonRequest.set("lastName", lastName);
    jsonRequest.set("accessToken", accessToken);
    std::ostringstream jsonBody;
    jsonRequest.stringify(jsonBody);

    Net::HTTPRequest request(Net::HTTPRequest::HTTP_POST, path, Net::HTTPMessage::HTTP_1_1);
    request.setContentType("application/json");
    request.setContentLength(jsonBody.str().length());
    session.sendRequest(request) << jsonBody.str();


I have 2 questions:

First, is it possible to send a POST request with a JSON body without specifying the content length header ? I tried appending 0x0d 0x0a to the end of the body to indicate termination but it didn't work... (I realize it's not a POCO specific question but a more general HTTP question)

Second, if it's not possible to avoid specifying the content-length header, is the above code correct? It seems a bit awkward to me.

Thanks,
BQ.
bquenin
 
Posts: 3
Joined: 22 Jan 2013, 02:09

Re: HTTPRequest, JSON & Content-Length

Postby bquenin » 26 Jan 2013, 14:05

Nevermind, I think I've found the answer to my own question:

Specifying the chunked transfer encoding solve my issue.

The code is now:

Code: Select all
    // Request
    JSON::Object jsonRequest;
    jsonRequest.set("firstName", firstName);
    jsonRequest.set("lastName", lastName);
    jsonRequest.set("accessToken", accessToken);

    Net::HTTPRequest request(Net::HTTPRequest::HTTP_POST, path, Net::HTTPMessage::HTTP_1_1);
    request.setContentType("application/json");
    request.setChunkedTransferEncoding(true);
    jsonRequest.stringify(session.sendRequest(request));


Seems way more straight forward now.

Thanks anyway :)
BQ.
bquenin
 
Posts: 3
Joined: 22 Jan 2013, 02:09


Return to Support

Who is online

Users browsing this forum: No registered users and 6 guests

cron