i want to consume a rest service, download the json and put it in a object, then return it, but the object always return me null, this is the class:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
Context ctx;
// constructor
public JSONParser(Context ctx) {
this.ctx = ctx;
}
public JSONObject getJSONFromUrl(String url) {
AsyncjSONTask task = new AsyncjSONTask();
task.execute(url);
return jObj;
}
private class AsyncjSONTask extends AsyncTask<String, Void, JSONObject>{
@Override
protected JSONObject doInBackground(String... params) {
String url = params[0];
InputStream is = null;
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
JSONObject jObjOut = null;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObjOut = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObjOut;
}
@Override
protected void onPostExecute(JSONObject jObjIn) {
jObj = jObjIn;
}
}
}
if there's another way to consume rest services, please tell me.