Android + PHP Background development

Source: Internet
Author: User
Tags php server

android+php the data interaction between Android and the server in our Android development, we can not avoid the login registration, personal information acquisition, data interaction and so on this series of operations. This requires the interaction of the Android side with the server side of the data. But how to get them to interact with the data, I also stepped on a lot of pits here, but finally it is interactive success, the following I put my method to write, dare not say is the best, at least can be used, but also please give us a lot of advice.

When I checked the data on the Internet, I found that there were many ways that Android would be able to use it on the server side. HttpClient, HttpResponse, Okhttpclient, HttpURLConnection, and so many other ways, But I found that there are a lot of ways in which the package used is not in the original class library (or I may not have found a suitable way to use it). Experiment to the end, I decided to use the HttpURLConnection class to achieve, because the feeling this does not need to download another library from the Internet, more simple and convenient, directly can be used. On the server side, I use the familiar apache+php to build.

The interaction between Android and PHP is implemented via HTTP network programming. The HTTP protocol needs to be adhered to. By http://www ... Domain name to achieve access. Use PHP files as an interface for remote operation of the database. The numeric transfer between Android and PHP is through the JSON data type. The following are specific Java and PHP processing for JSON data types. Let me show you.

The first step: first of all, you need to define the URL to access your server, you can directly fill in the IP address, you can also fill in the server to access the domain name information. For example you can fill in: http://www.myServer.com/test.php or http://111.111.111.11/test.php, with a URL class to convert.

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

The second step: set the parameters of the connection to set the parameters of the network connection, the use of post for data transmission, similar to the post delivery of the Web page.

//Set whether to output to httpurlconnection, because the POST request is set, the parameter is placed in the HTTP body, so it needs to be set to True, false by default;http.Setdooutput(true);//Set whether to read from HttpURLConnection, true by defaulthttp.Setdoinput(true);//Set Request modehttp.Setrequestmethod("POST");//Set POST request not to use cachehttp.setusecaches(false);//This setting is important, set the data type of the HTTP request and the encoding format, because JSON is used here to pass the data, so this setting is JSON.http.Setrequestproperty("Content-type","Application/json;charset=utf-8");//If you want to send pictures in the background, the settings here are somewhat different, of course there will be other differences, here first unknown. //http.setrequestproperty ("Connection", "keep-alive");//http.setrequestproperty ("Charset", "UTF-8");//http.setrequestproperty ("Content-type", "multipart/form-data;boundary=" + "* * * *");//Establish connectionhttp.Connect();//There will be some other parameters, the settings of this parameter can be selected according to their actual situation

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

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

Fourth step: Get the data returned by the server side.

//Get Web page return Data//Get input streamBufferedReader BufferedReader =NewBufferedReader (NewInputStreamReader (http.getInputStream())); String line =""; StringBuilder Builder =NewStringBuilder ();//Create an input buffer while(NULL! = (Line=bufferedreader.ReadLine())){//end reads into a null valueline =NewString (line.getBytes(),"Utf-8"); Builder.Append(line);//write buffers}string result = Builder.toString();//Return resultsBufferedReader.Close(); HTTP.Disconnect();//If the connection succeeds, the data returned in the background is recorded in the result. 

The fifth step is to parse the data to get the data returned in the background.

    //把获取的字符串通过转换成json形式的数据类型    JSONObject jsonObject=newJSONObject(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

PHP does not need to use $_post or $_request to receive the data when it receives the file. Because Android does not pass data from the form, it is a stream of data, so it needs to receive the input data stream.

$data=json_decode(file_get_contents("php://input"),true);$data[···] = ····;.....returnjson_encode([‘status‘=>1,"message"=>"成功接收数据"]);
Use the login instance I made to show all the code. Android side
Private int Login(String telephone,string password)throwsIOException, Jsonexception {intreturnresult=0;//Establish network connectionString urlstr="Your Server URL address"; URL url=NewURL (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();//Get input stream, want server to write dataOutputStream out=http.Getoutputstream();//post RequestJsonobject Data=New Jsonobject(); Data.put("Telephone", telephone); Data.put("Password", password); Out.Write(Data.toString().getBytes()); Out.Flush(); Out.Close();//Read the data returned by the webpageBufferedReader bufferedreader=NewBufferedReader (NewInputStreamReader (http.getInputStream()));//Get input streamString line=""; StringBuilder builder=NewStringBuilder ();//Create an input buffer         while(NULL! = (Line=bufferedreader.ReadLine())){//end reads into a null valueLine=NewString (line.getBytes(),"Utf-8"); Builder.Append(line);//write buffer} String Result=builder.toString();//Return resultsBufferedReader.Close(); http.Disconnect();Try{//Get JSON data returned by the serverJsonobject 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 ="no nickname entered"; }            }        }Catch(Jsonexception e) {Log.e("Log_tag","The Error parsing data"+e.toString()); }returnReturnresult; }
PHP side
functionLogin(){$value=Array();        $data=Array();        the//php file receives the data stream passed by the input port        $value=Json_decode(file_get_contents("Php://input"),true);        //Find the database and determine if the user exists        $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];}        }    }

The first time to build Android backstage, what is wrong with the place also please enlighten us.

Android + PHP Background development

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.