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 然後測試通過。