我想消費REST服務,下載JSON和把它放在一個對象,然後返回,但對象總是返回我空,這是類:JSON對象空的Android的AsyncTask
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;
}
}
}
如果還有其他方式可以使用休息服務,請告訴我。
在日誌中是否有錯誤? – dmon
爲什麼不通過它進行調試並找出它爲什麼是空的?你也似乎在做一個HTTP POST,你確定你想要的,而不是一個GET? – lahsrah