How do I get the HTTP request body in MY language?

From The Socknet

Jump to: navigation, search

The specification calls for the request body to contain nothing but a JSON object. This is unlike a "regular" POST call from a web page form, so it cannot be accessed by Perl's CGI::param or PHP's $_POST, for example.

The following examples show how to get the entire raw post data (first checking that the data was in fact POSTed and is reportedly application/json) in a few sample languages/libraries:

Contents

Perl's CGI.pm

$q = new CGI();
die 'Not a POST' unless $q->request_method eq 'POST';
die 'Not JSON' unless $ENV{CONTENT_TYPE} eq 'application/json';
$json_data = $q->param('POSTDATA');

Perl's Catalyst

Where $c is the context object.

die 'Not a POST' unless $c->request->method eq 'POST';
die 'Not JSON' unless $c->request->content_type eq 'application/json';
$json_data = $c->request->body;
$json_data = <$json_data> if ref $json_data;

PHP

if ($_SERVER['REQUEST_METHOD'] != 'POST')
    die('Not a POST');
if ($_SERVER['CONTENT_TYPE'] != 'application/json')
    die('Not JSON');
$json_data = file_get_contents('php://input');

Java

...
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, IllegalStateException
{
    if (! request.getContentType().equals("application/json"))
        throw new IOException("Not JSON");
    BufferedReader reader = request.getReader();
    char[] characters = new char[request.getContentLength()];
    reader.read(characters, 0, request.getContentLength());
    String json_data = new String(characters);
    ...
}
...

None of the above examples has been tested. Feel free to add more untested examples in other languages/libraries.

Also of note is that the result of all the examples is a string which may or may not actually be JSON. Now's the time to pass that into your JSON library's parse() function and find out if it works.

See Also

Personal tools