我正在尝试使用Android 4.0或更高版本中的HTTPCLient从JSON格式的网页获取数据。问题是httpclient成功获取了链接“http://extjs.org.cn/extjs/examples/grid/survey.html”的数据,但是我创建的页面“http://192.168.x.xxx:8888/xampp/jsonTest.php?type=1”和JSON页面输出失败了:
{“网络”:“好”}
有谁知道问题是什么?如果没有,是否有另一种方法可以使用我自己的页面读取JSON。
这是我写的代码。
public class MainActivity extends Activity {
public EditText edit;
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
} else {
Log.e("JSON", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
private class ReadJSONFeedTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
return readJSONFeed(urls[0]);
}
protected void onPostExecute(String result) {
try {
JSONArray jsonArray = new JSONArray(result);
Log.i("JSON", "Number of surveys in feed: " + jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Toast.makeText(getBaseContext(), jsonObject.getString("Network"),Toast.LENGTH_SHORT).show();
edit.setText("Check :" + jsonObject.getString("Network"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit = (EditText)findViewById(R.id.result1);
new ReadJSONFeedTask().execute("http://192.168.x.xxx:8888/xampp/jsonTest.php?type=1");
//new ReadJSONFeedTask().execute("http://extjs.org.cn/extjs/examples/grid/survey.html");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
PS。我完成了Internet访问权限