Send JSON-Object as POST in RequestBuilder

2,631 views
Skip to first unread message

couda

unread,
Dec 2, 2007, 9:01:35 AM12/2/07
to Google Web Toolkit
Hi all

I want to send a JSON-Object throw RequestBuilder to a Server, where
PHP works.
I'm trying to do that with a RequestBuilder like this.

JSONArray elements = new JSONArray();

for (int i = 0; i < 10; i++) {
JSONObject el1 = new JSONObject();
el1.put("sortid", new JSONNumber(1));
el1.put("label", new JSONString("Name"));
el1.put("name", new JSONString("name"));
el1.put("size", new JSONString("20"));
el1.put("maxLength", new JSONString("10"));
elements.set(i, el1);
}

JSONObject elementSet = new JSONObject();
elementSet.put("Elements", elements);

RequestBuilder rb = new RequestBuilder(RequestBuilder.POST,
SERVER_URL
+ "?request=json");
try {
rb.sendRequest(elementSet.toString(), new FormServerHandler());
} catch (RequestException e) {
GWT.log("Could not send save request", e);
}

But when I take a look in to the POST Message with the Firebug, there
is no POST content send.
The content of the JSON is written in to the Header -> Cache-Control:
no-cache -> {"Elements":[{"sortid":1, "label":"Name", "name":"name",
"size":"20", "maxLength":"10"},{"sortid":1, ..}]}

How can I put a JSON String in to a POST Message, so I can read the
POST on the server side with PHP?

Thank you for your answers.

Greets couda

mP

unread,
Dec 2, 2007, 3:14:19 PM12/2/07
to Google Web Toolkit
YOu might want to try the rocket lib which reuses the gwt rpc
interfaces but uses json to serialize/deserialize the request/
response. The mapping between class to json is achieved using javadoc
annotations.

Your rpc code using rocket's remoting json support would look
practically the same as regular gwt-rpc. If you use it you wont have
to muck about with RequestBuilder etc, check out the tests included in
the download to see how it all works.

Peter Blazejewicz

unread,
Dec 2, 2007, 3:53:40 PM12/2/07
to Google Web Toolkit
hi,
you should encode your params I think:

StringBuffer params = new StringBuffer();
params.append("request=json");
params.append("&");
params.append("jsonData=");
params.append(URL.encodeComponent(elementSet.toString());
//
RequestBuilder rb = new RequestBuilder(RequestBuilder.POST,
SERVER_URL);
//
rb.sendRequest(params.toString(), new FormServerHandler());

//

also you seems to want to use JSON-RPC, which can be done that way:

JSONArray elements = new JSONArray();
for (int i = 0; i < 10; i++) {
JSONObject el1 = new JSONObject();
el1.put("sortid", new JSONNumber(1));
el1.put("label", new JSONString("Name"));
el1.put("name", new JSONString("name"));
el1.put("size", new JSONString("20"));
el1.put("maxLength", new JSONString("10"));
elements.set(i, el1);
}
JSONObject jsonRPC = new JSONObject();
jsonRPC.put("method", new JSONString("echo"));
jsonRPC.put("params", elements);
jsonRPC.put("id", new JSONNumber(9D));
//
RequestBuilder rb = null;
rb = new RequestBuilder(RequestBuilder.POST, SERVER_URL);
// CONTENT TYPE
rb.setHeader("Content-Type", "application/json");
rb.setHeader("Accept", "application/json");
//
Request r = null;
try {
r = rb.sendRequest(URL.encodeComponent(jsonRPC.toString()),
new RequestCallback() {
/* @Override */
public void onError(Request request, Throwable exception) {
// TODO Auto-generated method stub
}

/* @Override */
public void onResponseReceived(Request request,
Response response) {
// RESPONSE IN JSON should look like:
// {"result":{echoedJSONData, "error":..., "id":9}
String jsonData = response.getText();
JSONValue jsonResponse = JSONParser.parse(jsonData);
// TODO Auto-generated method stub

}
});
} catch (RequestException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

on your server you can use any PHP JSON-RPC implementations (I've
checked and there are few written already),
on client you can either use GWT JSON implementation or use library
suggested by Miroslav to bind/build JSON objects,

regards
Peter

Reinier Zwitserloot

unread,
Dec 2, 2007, 9:52:53 PM12/2/07
to Google Web Toolkit
A few notes:

1) Peter... that's just wrong. It's POST, so there's a big difference
between adding stuff onto the URL and actually posting the string. The
only weirdness is tossing a GET parameter into a POST request, which
is a bit odd, but I think that usually works anyway. I toss my JSON to
my server that way (just passing the output of JSONObject.toString,
unencoded), and it works fine.

2) I think that the original poster ('couda') forgot all about the
Same Origin Policy. Unless SERVER_URL is the same, and therefore,
superfluous, or a string that starts with the path and not with
http(s)://, it wouldn't work because of SOP. couda: Google "Same
Origin Policy" and be enlightened.

On Dec 2, 3:01 pm, couda <danilo.co...@ggaweb.ch> wrote:

Peter Blazejewicz

unread,
Dec 4, 2007, 3:30:53 PM12/4/07
to Google Web Toolkit
hi Reinier,
well, you are correct: POST encoding ;)
my fault (was writing late in evening)
regards,
Peter

couda

unread,
Dec 4, 2007, 4:17:58 PM12/4/07
to Google Web Toolkit
Thank you for your answers. But there is something else what i don't
understand.
When I send the JSON to the Server, there is no POST attribute, where
i can read the JSON Message. Normally I can get it with
$_POST['name'], but when I don't declare a variable for the JSON
Message, how can I get the JSON?

Greets couda

Peter Blazejewicz

unread,
Dec 4, 2007, 6:47:01 PM12/4/07
to Google Web Toolkit
hi,

if you just write JSON string into POST request with header set to
"application/json":

rb.setHeader("Content-Type", "application/json");

you don't need anything else, just check header value and parse raw
request data on your server (I don't remember PHP well enough to state
which variable is for reading raw request data),

regards,
Peter

Reinier Zwitserloot

unread,
Dec 5, 2007, 6:56:23 AM12/5/07
to Google Web Toolkit
$_POST in PHP parses www-form-data encoded stuff. JSON is something
else. You'll need to ask on a PHP related forum on how to get the raw
post data out.

On Dec 4, 10:17 pm, couda <danilo.co...@ggaweb.ch> wrote:

Tom Schindl

unread,
Dec 5, 2007, 8:49:38 AM12/5/07
to Google-We...@googlegroups.com
We are sending values to a PHP-Service using:

----------8<----------
HTTPRequest.asyncPost(GWT.getModuleBaseURL() +
"/services/persistComponent.php",jObject.toString(),new
JSONResponseTextHandler(cb));
----------8<----------

and are reading values in PHP using:
----------8<----------
$slurp = file_get_contents("php://input");
$storeRequest = json_decode( $slurp, true );
----------8<----------

The only thing you need to take care then is that PHP is buggy when it
comes to escaped high-bit chars :-(

rta...@gmail.com

unread,
Dec 16, 2007, 10:23:36 PM12/16/07
to Google Web Toolkit
hi,

If you want to send Json encoded stuff from GWT to PHP, the basics are
pretty simple

1) create your

JSONObject request = new JSONObject();
request.put("hello", new JsonString("world"));

etc .. for all the other stuff you want there

String postData = request.toString();

2) send your stuff with GWT RequestBuilder

RequestBuilder builder = new RequestBuilder(RequestBuilder.POST,
"MyPage.php");
builder.sendRequest(postData, new RequestCallback() { ... });

3) on your php page decode the post stuff

$rawData = file_get_contents('php://input');
$postData = json_decode($postData, true);

$postData is an array and

$postData['hello'] == 'world'

4) if you want to send a reply to your gwt page

$reply = array("foo" => "bar");

print(json_encode($reply);

There's a few most problems if you want to send fancy characters,
international stuff and such, you need to UTF8 encode and decode your
stuff.

Also, look up my project http://code.google.com/p/lacertae/ it does
most of this stuff for you.

On Dec 5, 8:49 am, "Tom Schindl" <tomson...@gmail.com> wrote:
> We are sending values to a PHP-Service using:
>
> ----------8<----------
> HTTPRequest.asyncPost(GWT.getModuleBaseURL() +
> "/services/persistComponent.php",jObject.toString(),new
> JSONResponseTextHandler(cb));
> ----------8<----------
>
> and are reading values in PHP using:
> ----------8<----------
> $slurp = file_get_contents("php://input");
> $storeRequest = json_decode( $slurp, true );
> ----------8<----------
>
> The only thing you need to take care then is that PHP is buggy when it
> comes to escaped high-bit chars :-(
>
Reply all
Reply to author
Forward
0 new messages