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

1.[代码]php代码

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

2.[代码]java代码

01 privatevoidstartUrlCheck(String username,String password)
02 {
03 HttpClient client =newDefaultHttpClient();
04 StringBuilder builder =newStringBuilder();
05
06 HttpGet myget =newHttpGet("http://10.0.2.2/Android/index.php");
07 try{
08 HttpResponse response = client.execute(myget);
09 BufferedReader reader =newBufferedReader(newInputStreamReader(
10 response.getEntity().getContent()));
11 for(String s = reader.readLine(); s !=null; s = reader.readLine()) {
12 builder.append(s);
13 }
14 JSONObject jsonObject =newJSONObject(builder.toString());
15 String re_username = jsonObject.getString("username");
16 String re_password = jsonObject.getString("password");
17 intre_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
09 就加在
10
11 之前就好了
12 然后测试通过。

你可能感兴趣的:(怎样在Android访问php取回json数据)