我想消费一个rest服务,下载json放到一个对象中,然后返回,但是对象总是返回null,这是类:
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;
}
}
}
如果有其他消费休息服务的方式,请告诉我。
最佳答案
- 请确保您要执行 HTTP POST 而不是 GET。
- 在阅读响应之前,最好检查 HTTP 响应状态是什么
- 不要将异步代码包装在非异步类中?看来您感到困惑并称它为好像它不是异步的。
您的 JSONParser 类假设 AsyncTask 不是 Async,而实际上它是。这是您将如何做您想做的事情的示例:
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
new AsyncJsonTask(this).execute();
}
public void doSomethingWithTheResult(JsonObject result) {
// Show the result on the View or do whatever with it.
}
private class AsyncJsonTask extends AsyncTask<String, Void, JsonObject> {
private MainActivity _activity;
public AsyncJsonTask(MainActivity activity) {
this._activity = activity;
}
@Override
protected JsonObject doInBackground(String... params) {
JsonObject outputObject = null;
// Call your web service to return the output
// ...
return outputObject
}
@Override
protected void onPostExecute(JsonObject result) {
_activity.doSomethingWithTheResult(result);
}
}
}
关于android - JSON 对象 null Android AsyncTask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13713751/