怎样在Android访问php取回json数据

1. [代码]php代码     

1 $array array(
2   'username'=>'杨铸',
3   'password'=>'123456',
4   'user_id'=>1
5 );
6 echo json_encode($array);

2. [代码]java代码     

01 private void startUrlCheck(String username,String password)
02 {
03     HttpClient client = new DefaultHttpClient();
04     StringBuilder builder = new StringBuilder();
05
06     HttpGet myget = new HttpGet("http://10.0.2.2/Android/index.php");
07     try {
08         HttpResponse response = client.execute(myget);
09         BufferedReader reader = new BufferedReader(new InputStreamReader(
10         response.getEntity().getContent()));
11         for (String s = reader.readLine(); s != null; s = reader.readLine()) {
12             builder.append(s);
13         }
14         JSONObject jsonObject = new JSONObject(builder.toString());
15         String re_username = jsonObject.getString("username");
16         String re_password = jsonObject.getString("password");
17         int re_user_id = jsonObject.getInt("user_id");
18         setTitle("用户id_"+re_user_id);
19         Log.v("url response""true="+re_username);
20         Log.v("url response""true="+re_password);
21     catch (Exception e) {
22         Log.v("url response""false");
23         e.printStackTrace();
24     }
25 }

3. [代码]运行说明     

01 其中http://10.0.2.2为Android访问本机url的ip地址。对应电脑上测试的http://127.0.0.1
02
03 另外执行代码时会抛出异常
04
05 java.net.SocketException: Permission denied
06
07 此为应用访问网络的权限不足 在AndroidManifest.xml中,需要进行如下配置:
08 <uses-permission Android:name="android.permission.INTERNET" />
09 就加在
10 </manifest>
11 之前就好了
12 然后测试通过。
分享到: 

标签