mjoger
mjoger

Reputation: 25

How receive JSON object via HttpClient?

I use HttpClient in android to send post request:

    HttpClient client = new DefaultHttpClient();

    HttpPost request = new HttpPost(hostNameCollection);

    StringEntity se = new StringEntity(jsonObj.toString());

    request.setHeader("Accept", "application/json");
    request.setHeader("Content-type", "application/json");


    request.setEntity(se);
    HttpResponse response = client.execute(request);

    Log.v("HttpLogClient.logJSONObject", "wyslano JSON");

and I'dont know how I can receive JSON object on my Java EE servlet.

Upvotes: 0

Views: 1647

Answers (3)

eugen
eugen

Reputation: 5916

If you are using plain servlets the json stream is located in the body of the HttpServletRequest : request.getReader() or request.getInputStream();

To make things easier you could use a library handling databinding for you. Have a look at Genson http://code.google.com/p/genson/.

YouClass object = new Genson().deserialize(request.getReader(), YourClass.class);
// or to a plain map
Map<String, Object> map = genson.deserialize(request.getReader(), Map.class);

Upvotes: 0

Robert Rowntree
Robert Rowntree

Reputation: 6289

read the body of the http post ( server-side ) by getting the a stream object on the body and then reading it.

Once youve read it , convert the bytes to chars and that will be json which you can use to build a json object like a jsonNode using 'jackson' libs.

Upvotes: 0

Jeffrey Blattman
Jeffrey Blattman

Reputation: 22637

you need to read the response body text, then parse as JSON,

String result = EntityUtils.toString(response.getEntity());
JSONObject jo = new JSONObject(result);

Upvotes: 2

Related Questions