安卓app客户端访问php服务器数据交互

客户端使用httpclient与服务器数据交互是,类似在网页上提交一个表单,设定表单里各个input的名字,值,选择method为POST或GET,设置处理action的php文件,在安卓里也是类似的,把参数以键值对的形式存入一个参数列表,选择HTTP POST方法或者GET方法, 选择相应的类HttpPost或者HttpGet 并在构造方法传入php文件的url Php文件接受到请求后,会把参数放到一个超全局变量 POSTPOST _GET(请求用了GET方法)数组中,可以以参数名字为键访问参数的值。

在给出一个简单例子之前,先提醒一下,安卓xml配置文件中要加入INTERNET权限,而且httpclient调用相关逻辑代码不能在oncreate()方法里调用,要想调用一种解决方法是加代码强制执行,另一种是开启新的线程进行处理,本文采取后一种方式。

安卓客户端:

import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {


    private String strResult="";  


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        //在新线程里发送请求并获得返回结果字符串,把值赋给strResult  
        new Thread(new RequestThread()).start();  


      //点击按钮更新TextView的内容  
        final TextView tv = (TextView) findViewById(R.id.tv);  
        Button b1 = (Button) findViewById(R.id.button1);
        b1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                tv.setText(strResult);  
            }
        });
    }

    private class RequestThread implements Runnable{

        @Override
        public void run() {
            //因为选择POST方法,所以new HttpPost对象,构造方法传入处理请求php文件的url  
            HttpPost httpRequest = new HttpPost("http://192.168.1.103/test/c2sdatademo.php"); 
            //POST方法的参数列表  
            ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();  
            //添加名为userName的参数,值为giantpoplar  
            params.add(new BasicNameValuePair("userName", "haoxingxing"));  

            try {  
                //设置请求实体,设定了参数列表  
                httpRequest.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));  
                //执行请求,等待服务器返回结果  
                HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);  
                //log出http返回报文头  
                Log.e("status",httpResponse.getStatusLine().toString());  
                //判断返回码是否为200,200表示请求成功  
                if (httpResponse.getStatusLine().getStatusCode() == 200) {  
                    //获取返回字符串  
                    strResult = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);  

                }  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />

</LinearLayout>

权限

    <uses-permission android:name="android.permission.INTERNET"/>

php服务器端
c2sdatademo.php

<?php  
//以参数名userName访问值  
$user_name = $_POST['userName'];  
//echo 的结果会返回给安卓客户端,客户端程序里把下面echo  
//的内容赋值给了变量strResult  
echo "hello, ".$user_name."!";  

?>  

源代码地址:http://download.csdn.net/detail/ruishaoma8471/9897932

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值