Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android獲取php簡單數據

android獲取php簡單數據

編輯:關於Android編程

一  android獲取php數據 步驟: 1 加入權限: <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />     2啟動一個新線程 android4.0開始不允許直接在ui線程直接操作httpClient     3 注意url:http://10.0.2.2/testAndroid.php (不要填寫:127.0.0.1 這個是本機電腦的,模擬器有自己的默認ip)     4通過handler將數據從新線程中傳送出來     MainActivity.java======================     public class MainActivity extends Activity {      public final static String EXTRA_MESSAGE = "com.example.myapp.MESSAGE"; HttpClient client; public String res; public Handler myHandler; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);   myHandler = new Handler(){ public void handleMessage(Message msg){ if(msg.what == 0x123){ Toast toast = Toast.makeText(MainActivity.this,msg.obj.toString(),Toast.LENGTH_SHORT); toast.show(); } } }; } public void sendMessage(View view) { startUrlCheck();     }         private void startUrlCheck()         {  new Thread(){ public void run(){ client = new DefaultHttpClient();  StringBuilder builder = new StringBuilder();  HttpGet myget = new HttpGet("http://10.0.2.2/testAndroid.php");  //HttpGet myget = new HttpGet("http://www.crazyit.org");  try {  HttpResponse response = client.execute(myget);  HttpEntity entity = response.getEntity(); BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));  for (String s = reader.readLine(); s != null; s = reader.readLine()) {  builder.append(s);  }  JSONObject jsonObject = new JSONObject(builder.toString());  String re_password = jsonObject.getString("password");      res = re_password;     Message msg = new Message();     msg.what = 0x123;     msg.obj = res;     myHandler.sendMessage(msg);   } catch (Exception e) {  e.printStackTrace();  }  } }.start();   } }     testAndroid.php===================================     <?php $array = array(  'username'=>'楊鑄',  'password'=>'123456',  'user_id'=>1  );  echo json_encode($array);  ?>
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved