我正在尝试使用 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;
}
}
附言。我做了互联网访问权限