Simple interaction between Android client and PHP Server & logon to registered instances

Source: Internet
Author: User
Simple interaction between the Android client and the PHP Server & logon to the registered instance server uses a local apache server. all PHP files are written in the D: \ AppServ \ www directory .. I have been writing the request code, but it has never been successful because the request url is faulty .. The requested url must be the same as the port number on your server. How to change the port number, see http://jingyan.baidu.com/article/a65957f4fe8ec424e67f9bff.html

After setting your own port number, pay attention to the request url format:

The address for saving the php file locally is D: \ AppServ \ www \ get_data.json.

In the android client: url -------------- "http: // 10.0.2.2: 8080/get_data.json"
On the webpage: HTTP http: // 127.0.0.1: 8080/get_data.json/

It must be correct here .. Then start apache


I. client preparation

You need to add network permissions. because network requests are time-consuming, the request content is written in a subclass of inheritance and thread.

1. MainActivity. java

package com.example.log_user;import android.support.v7.app.ActionBarActivity;import android.support.v7.app.ActionBar;import android.support.v4.app.Fragment;import android.os.Bundle;import android.util.Log;import android.view.LayoutInflater;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.View.OnClickListener;import android.view.ViewGroup;import android.widget.Button;import android.widget.EditText;import android.os.Build;public class MainActivity extends ActionBarActivity {EditText user_name;EditText pass_word;Button login;Button zhuce;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        user_name=(EditText) findViewById(R.id.editText1);        pass_word=(EditText) findViewById(R.id.editText2);        login=(Button) findViewById(R.id.button1);        zhuce=(Button) findViewById(R.id.button2);                                          login.setOnClickListener(new OnClickListener(){                String url="http://10.0.2.2:8080/config.inc.php";@Overridepublic void onClick(View arg0) {    String user=user_name.getText().toString();    String pass=pass_word.getText().toString();// TODO Auto-generated method stub  new LoginThread(user,pass,url).start();        Log.d("MAIN","-------------------->MAINSUCCESS");        }                });                zhuce.setOnClickListener(new OnClickListener(){        String url="http://10.0.2.2:8080/test_signup.php";@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubString user=user_name.getText().toString();    String pass=pass_word.getText().toString();    new signup(user,pass,url).start();    Log.d("Main","------------------->signupsuccess");}                });                                          }}




2. LoginThread. java login

To put it simply, this class has made many mistakes because it was not aware of the need to create a subthread. Inherit from thread and put the operations to be executed in the run method. The gotoLogin method is used to determine whether the input username and password match the fields in the database connected to the server. HttpClient is used to process post requests. you need to put the transmitted data in this array.

ArrayList
 
    params
 
After the post request is executed
HttpResponse respose=client.execute(post);
An httpresponse is returned. after this object is converted to a string, it is actually the string echo from the php url page of the request.



String content=EntityUtils.toString(respose.getEntity());



Package com. example. log_user; import java. io. IOException; import java. io. unsupportedEncodingException; import java. util. arrayList; import java. util. list; import org. apache. http. httpEntity; import org. apache. http. httpResponse; import org. apache. http. httpStatus; import org. apache. http. nameValuePair; import org. apache. http. client. clientProtocolException; import org. apache. http. client. httpClient; 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. content. res. resources. theme; import android. util. log; import android. widget. toast; public class LoginThread extends Thread {String username; String password; String Url; @ Overridepublic void run () {// TODO Auto-generated method stubsuper. run (); Log. d ("run", "--------------------> MAINSUCCESS"); boolean isLoginSuccess = gotoLogin (username, password, Url); if (isLoginSuccess) {Log. d ("Log", "---------------------> logon successful");} else {Log. d ("Log", "---------------------> logon failed") ;}} public LoginThread (String user, String pass, String url) {this. username = user; this. password = pass; this. url = url;} public boolean gotoLogin (String user, String pass, String url) {boolean issuccess = false; String result; // send the post request HttpClient client = new DefaultHttpClient (); httpPost post = new HttpPost (url); // The Post operation transfer variable must use the NameValuePair [] array to store the ArrayList
 
  
Params = new ArrayList
  
   
(); Params. add (new BasicNameValuePair ("name", user); params. add (new BasicNameValuePair ("password", pass); try {post. setEntity (new UrlEncodedFormEntity (params); try {HttpResponse respose=client.exe cute (post); if (respose. getStatusLine (). getStatusCode () = HttpStatus. SC _ OK) {String content = EntityUtils. toString (respose. getEntity (); Log. d ("post", "---------------------> success"); Log. d ("post", content + ""); if (content. equals ("logsuccess") {issuccess = true ;}} else {Log. d ("post", "---------------------> failes") ;}} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke. printStackTrace ();} return issuccess ;}}
  
 
3. signup. java registration page: Similar to logon principles



package com.example.log_user;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.util.ArrayList;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.NameValuePair;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;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.util.EntityUtils;import android.util.Log;public class signup extends Thread {private String username;private String password;private String url;@Overridepublic void run() {// TODO Auto-generated method stubsuper.run();boolean issuccess=doPOSThttp(username,password,url);if(issuccess){Log.d("sign","-------------->signsuccess");}else{Log.d("sign","-------------->signfailue");}}public signup(String user,String password,String url){this.username=user;this.password=password;this.url=url;}public   boolean  doPOSThttp(String username,String password,String url){boolean issuccess=false;HttpClient client=new DefaultHttpClient();HttpPost post =new HttpPost(url);ArrayList
 
   param=new ArrayList
  
   ();param.add(new BasicNameValuePair("name",username));param.add(new BasicNameValuePair("password",password));try {post.setEntity(new UrlEncodedFormEntity(param));try {HttpResponse response=client.execute(post);if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){String cont=EntityUtils.toString(response.getEntity());Log.d("post","------------>"+cont);if(cont.equals("signsuccess")){issuccess=false;}}} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();}return issuccess;}}
  
 




II. Server preparation

1. config. inc. php corresponds to the logon request of the client. The data passed through the $ _ POST method is matched by the data in the database. if the matching is successful, echo an identifier string used by the client to obtain the string for determination using response.


 


2. test_signup.php corresponds to the client registration request.

 

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.