android获取php简单数据

一  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); 
?>

你可能感兴趣的:(线程,数据,NetWork,Android4.0)