这是我在 AsyncTask 中使用的代码
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(request);
HttpEntity responseEntity = response.getEntity();
char[] buffer = new char[(int)responseEntity.getContentLength()];
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer);
stream.close();
result = new String(buffer);
return result;
这将返回一个字符串结果,并在我的 onPostExecute 方法中尝试解析该输入字符串:
JSONObject vehicle = new JSONObject(new String(result));
makeEdit.setText(vehicle.getString("make"));
plateEdit.setText(vehicle.getString("plate"));
modelEdit.setText(vehicle.getString("model"));
yearEdit.setText(vehicle.getString("year"));
一旦它到达 makeEdit.setText 它就会抛出一个错误 - make 没有价值。我对android还是很陌生,所以如果有明显的错误,不要发送死亡威胁。输入文本是以下 JSON 字符串:
{"GetJSONObjectResult":{"make":"Ford","model":"Focus","plate":"XXO123GP","year":2006}}