android - Reason why i'm not getting Json Response from server -
public string post(string url){ inputstream inputstream = null; string result = ""; try { // 1. create httpclient httpclient httpclient = new defaulthttpclient(); // 2. make post request given url httppost httppost = new httppost(url); string json = ""; // 3. build jsonobject jsonobject jsonobject = new jsonobject(); jsonobject.accumulate("username","example@gmail.com"); jsonobject.accumulate("password","123456!"); jsonobject.accumulate("appid","andapp"); // 4. convert jsonobject json string json = jsonobject.tostring(); // ** alternative way convert person object json string usin jackson lib // objectmapper mapper = new objectmapper(); // json = mapper.writevalueasstring(person); // 5. set json stringentity stringentity se = new stringentity(json); // 6. set httppost entity httppost.setentity(se); // 7. set headers inform server type of content httppost.setheader("accept", "application/json"); httppost.setheader("content-type", "application/json"); // 8. execute post request given url httpresponse httpresponse = httpclient.execute(httppost); toast.maketext(getbasecontext()," text",toast.length_short).show(); // 9. receive response inputstream inputstream = httpresponse.getentity().getcontent(); // 10. convert inputstream string if(inputstream != null) result = convertinputstreamtostring(inputstream); else result = "did not work!"; } catch (exception e) { log.d("inputstream", e.getlocalizedmessage()); } // 11. return result return result; } private class httpasynctask extends asynctask<string, void, string> { @override protected string doinbackground(string... urls) { // toast.maketext(getbasecontext(), "post invoked", toast.length_short).show(); return post(urls[0]); } // onpostexecute displays results of asynctask. @override protected void onpostexecute(string result) { toast.maketext(getbasecontext(), "data sent!"+result+" don", toast.length_long).show(); } } private static string convertinputstreamtostring(inputstream inputstream) throws ioexception{ bufferedreader bufferedreader = new bufferedreader( new inputstreamreader(inputstream)); string line = ""; string result = ""; while((line = bufferedreader.readline()) != null) result += line; inputstream.close(); return result; }
i tried invoke post method object of httpasynctask class, targeted url passed. toast execeuted in onpostexecute() popping message "data sent!done", tells value of 'result' variable null. why getting this? fault? please fix this.
Comments
Post a Comment