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将数据从新线程中传送出来
步骤:
1 创建一个httpClient 对象
2 使用post发送数据 创建一个HttpPost对象
3 设置请求参数用setEntity()
4 调用httpClient对象的execute() 发送请求,返回一个HttpResponse
5 调用HttpResponse的getEntity() 方法可以获取HttpEntity 对象
android =============================================
HttpClient client = new DefaultHttpClient();
StringBuilder builder = new StringBuilder();
HttpPost post = new HttpPost("http://10.0.2.2/testAndroid.php");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name","linzhouzhi"));
try {
post.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
try {
HttpResponse response = client.execute(post);
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 name = jsonObject.getString("name");
Message msg = new Message();
msg.what = 0x123;
msg.obj = name;
myHandler.sendMessage(msg);
php======================================================
<?php
if($_POST['name']=='linzhouzhi'){
$array = array( 'name'=>'linzhouzhi');
echo json_encode($array);
}else{
$array = array('name'=>'err');
echo json_encode($array);
}
?>