Sunday, 15 March 2015

Sending JSON request POST in android -



Sending JSON request POST in android -

i'm trying send json post request : http://5.101.97.65:3000/en/api/sessions

post request construction :

{user: {email: 'value', password: 'value '} }

response should :

{"success":true or false,"info":"...","data":{"auth_token":"...."}}

for illustration normaly should homecoming true value "success" key :

{"user":{"email":"user@example.com","password":"changeme"}}

and code :

final string myurl ="http://5.101.97.65:3000/api/sessions"; string result = null; string params = "{\"user\":{\"email\":\"user@example.com\",\"password\":\"changeme\"}}"; seek { resthandler rh = new resthandler(); result = rh.getresponse(myurl, 2, params); jsonobject rs = new jsonobject(result); if (rs.getboolean("success")) homecoming "good"; else homecoming "baad"; } grab (exception e){ e.printstacktrace(); homecoming "baaad"; }

the resthandler class (function getresponse ) :

public string getresponse (string url, int method, string params) { seek { // http client httpclient httpclient = new defaulthttpclient(new basichttpparams()); httpentity httpentity = null; httpresponse httpresponse = null; // checking http request method type if (method == 2) { httppost httppost = new httppost(url); if (params != null) { httppost.setheader("content-type", "application/json"); httppost.setentity(new stringentity(params, "utf8")); } httpresponse = httpclient.execute(httppost); } else if (method == 1) { // code httpget not needed here } httpentity = httpresponse.getentity(); response = entityutils.tostring(httpentity); httpclient = null; httpentity = null; httpresponse = null; } grab (unsupportedencodingexception e) { e.printstacktrace(); } grab (clientprotocolexception e) { e.printstacktrace(); } grab (ioexception e) { e.printstacktrace(); } homecoming response; }

the problem i'm getting result html code of error page not json response. what's wrong in code ?

the problem when send post request sended plaintext have changed :

httpclient httpclient = new defaulthttpclient(new basichttpparams());

to :

httpclient httpclient = new defaulthttpclient();

and have added :

httppost.addheader("accept", "application/json");

to slove problem of 422 unprocessable entity on response.

final code (the updated part only)

httpclient httpclient = new defaulthttpclient(); httpentity httpentity = null; httpresponse httpresponse = null; // checking http request method type if (method == post) { httppost httppost = new httppost(url); if (params != null) { httppost.setheader("content-type", "application/json"); httppost.addheader("accept", "application/json"); httppost.setentity(new stringentity(params)); }

android json rest

No comments:

Post a Comment