我想消费一个休息服务,下载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;
}
}
}
如果还有其他消费休息服务的方式,请告诉我。