android + php background development

android+php Android and server data interaction

When we develop android, we cannot avoid a series of operations such as login and registration, personal information acquisition, data interaction and so on. In this way, data interaction between the android side and the server side is required. But how to make them interact with data, I have also stepped on a lot of pits here, but in the end, the interaction is successful. I will write my method below, I dare not say it is the best, at least it can be used Yes, please advise.

When looking up information on the Internet, I found that there are many methods that android can use to transmit data to the server. There are many methods such as HttpClient, HttpResponse, OkHttpClient, HttpURLConnection, etc., but I found that there are many methods in the package that do not exist in the most primitive class library (maybe I have not found a suitable method). At the end of the experiment, I decided to use the HttpURLConnection class to implement it, because I feel that this does not need to download other class libraries from the Internet, it is relatively simple and convenient, and can be used directly. On the server side, I use Apache+php, which I am familiar with, to build.

The interaction between android and PHP is realized through http network programming. Need to comply with the http protocol. Access is achieved through the http://www...... domain name. Use PHP files as an interface for remote database operations. The value transfer between android and PHP is through the json data type. There will be specific java and PHP processing of json data type below. I'll show it below.

Step 1: First, you need to define the url address that can access your server. You can directly fill in the IP address, or you can fill in the domain name information that can access the server. For example, you can fill in: http://www.myServer.com/test.php or http://111.111.111.11/test.php, and convert it with a URl class .

//建立网络连接
String url_str= "http://111.111.111.11/test.php";
URL url=new URL(url_str);
HttpURLConnection http = (HttpURLConnection)url.openConnection();

Step 2: Set the parameters of the connection Set some parameters of the network connection, and use the post to transmit data, which is similar to the post transmission of the web page.

//设置是否向httpUrlConnection 输出,因为设置的是post请求,参数放在http正文中,因此需要设为true,默认情况下是false;
http.setDoOutput(true);
//设置是否从httpUrlConnection读入,默认情况下是true
http.setDoInput(true);
//设置请求方式
http.setRequestMethod("POST");
//设置 post请求不能使用缓存
http.setUseCaches(false);
//这个设置比较重要,设置http请求的数据类型以及编码格式,因为这里使用json来传递数据,所以这一设置是json.
http.setRequestProperty("Content-type", "application/json;charset=utf-8");
//如果想要往后台传递图片的话,这里的设置有些不同,当然还会有其他的不同,这里先不详解了。
//http.setRequestProperty("Connection", "Keep-Alive");
//http.setRequestProperty("Charset", "UTF-8");
//http.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + "****");
//建立连接
http.connect();

//还会有一些其他参数,这个参数的设置可以根据自己的实际情况进行选择

Step 3: Get the input stream and write the data to be passed.

 OutputStream out=http.getOutputStream();
 //创建json对象并添加数据。
 data = new JSONObject();
 data.put("name","Myname");
 data.put("password","MyPassword");
 
 //post请求
out.write(data.toString().getBytes());
out.flush();
out.close();

Step 4: Get the data returned by the server.

//获取网页返回数据
//获取输入流
BufferedReader bufferedReader =new BufferedReader(new InputStreamReader(http.getInputStream()));
String line ="";
StringBuilder builder = new StringBuilder(); //建立输入缓冲区
while(null != (line=bufferedReader.readLine())){ //结束会读入一个null值
            line = new String(line.getBytes(),"utf-8");
            builder.append(line); //写入缓冲区
     }
String result = builder.toString(); //返回结果
bufferedReader.close();
http.disconnect();

//如果连接成功result里面记录的是后台返回的数据。

The fifth step is to analyze the data and obtain the data returned by the background.

    //把获取的字符串通过转换成json形式的数据类型
    JSONObject jsonObject=new JSONObject(result);
    //获取里面的数据
    returnResult=jsonObject.getInt("status");
    if(returnResult !=0){ 
    //如果返回的json里还有数组,需要用jsonArray进行获取,然后再从获取的数据里逐个获取json数据。
    user_account=jsonObject.getString("telephone");
    address=jsonObject.getString("address");
    username=jsonObject.getString("username");
    sex=jsonObject.getString("sex");
   
    

PHP server side

When PHP receives files, it is no longer necessary to use $_POST or $_REQUEST to receive data. Because what android passes is not the data of the form, but a data stream, it needs to receive the input data stream.

$data=json_decode(file_get_contents("php://input"),true);
$data[···] = ····;

.....


return json_encode(['status'=>1,"message"=>"成功接收数据"]);

Take the login example I made to show all the code.

android side
private int login(String telephone,String password) throws IOException, JSONException {
        int returnResult=0;

        //建立网络连接
        String urlstr="你的服务器url地址";
        URL url=new URL(urlstr);
        HttpURLConnection http=(HttpURLConnection)url.openConnection();

        http.setDoOutput(true);
        http.setDoInput(true);
        http.setRequestMethod("POST");
        http.setUseCaches(false);
        http.setRequestProperty("Content-type", "application/json;charset=utf-8");
        http.connect();

        //获取输入流,想服务器写入数据
        OutputStream out=http.getOutputStream();
        //post请求
        JSONObject data=new JSONObject();
        data.put("telephone",telephone);
        data.put("password",password);
        out.write(data.toString().getBytes());
        out.flush();
        out.close();

        //读取网页返回的数据
        BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(http.getInputStream()));//获取输入流
        String line="";
        StringBuilder builder=new StringBuilder();//建立输入缓冲区
        while(null !=(line=bufferedReader.readLine())){ //结束会读入一个null值
            line=new String(line.getBytes(),"utf-8");
            builder.append(line); //写缓冲区
        }
        String result=builder.toString(); //返回结果
        bufferedReader.close();
        http.disconnect();

        try{
            //获取服务器返回的Json数据
            JSONObject jsonObject=new JSONObject(result);
            returnResult=jsonObject.getInt("status");
            if(returnResult !=0){
                user_account=jsonObject.getString("telephone");
                address=jsonObject.getString("address");
                username=jsonObject.getString("username");
                sex=jsonObject.getString("sex");
                if(username == null){
                    username ="未输入昵称";
                }
            }

        } catch (JSONException e) {
            Log.e("log_tag", "the Error parsing data "+e.toString());
        }
        return returnResult;

    }

php side

function Login(){
        $value=array();
        $data=array();

        //php文件接收输入端传递的数据流
        $value=json_decode(file_get_contents("php://input"),true);
        //查找数据库,判断是否存在该用户
        $login=Db::name("Db_name")->where('telephone',$value['telephone'])->find();
        if(!$login){
            return ['status'=>0];
        }else{
            $password=md5($value['password']);
            if($password == $login['password']){
                return ['status'=>$login['id'],"telephone"=>$login['telephone'],'username'=>$login["username"],"address"=>$login["address"],"sex"=>$login["sex"]];
            }else{
                return ['status'=>0];
            }
        }

    }

It is the first time to build the background of android, if there is anything wrong, please feel free to let me know.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325247615&siteId=291194637