Login authentication example tutorial developed by Android

  • 2020-06-07 05:15:56
  • OfStack

The example described in this paper is derived from the login verification function developed in one project. The specific requirement is to enter the user name and password on the Android side and verify whether there is this user in the MySQL database on the server side. Before the implementation, of course, the first thing is how to send the data on the Android side to the server side.

Server side: ES6en. java code as follows:


public class ManageServlet extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    response.setCharacterEncoding("utf-8");
    String name = request.getParameter("name");
    String password = request.getParameter("password");
    System.out.println(" User name: "+name+"  Password: "+password);
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
  }
}

What we have achieved here is just to print out the data of the client in the console. I believe that those who have learned jsp development are the best. The rest of the data verification should not be discussed here.

Next up is the Android end:

Main activity: MainActivity. java page code is as follows:


public class MainActivity extends Activity {
  private EditText textname = null;
  private EditText textpassword = null;
  private Button button = null;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
     
    textname = (EditText)findViewById(R.id.name);
    textpassword = (EditText)findViewById(R.id.password);
    button = (Button)findViewById(R.id.button);
     
    button.setOnClickListener(new mybuttonlistener());
     
  }
  class mybuttonlistener implements OnClickListener{
    boolean result=false;
    String name;
    String password;
    public void onClick(View v) {
      try {        
        name = textname.getText().toString();
        name = new String(name.getBytes("ISO8859-1"), "UTF-8");
        password = textpassword.getText().toString();
        password = new String(password.getBytes("ISO8859-1"), "UTF-8");
      } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
      }
      try {
        result = NewsService.save(name,password);
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      if(result){
        Toast.makeText(MainActivity.this, R.string.ok, Toast.LENGTH_SHORT).show();
      }else{
        Toast.makeText(MainActivity.this, R.string.error, Toast.LENGTH_SHORT).show();
      }
    }
  }
}

The layout file is as follows:


<RelativeLayout 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"
  tools:context="${relativePackage}.${activityClass}"
  >
  <LinearLayout 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    >
    <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/name" />
    <EditText 
      android:id="@+id/name"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:hint="@string/playname"
      android:singleLine="true"
      />
    <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/password" />
    <EditText 
      android:id="@+id/password"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:password="true"
      android:hint="@string/playpass"
      android:singleLine="true"
      />
    <Button 
      android:id="@+id/button"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:onClick=""
      android:text="@string/submit"
      />
  </LinearLayout>
</RelativeLayout>

service (NewsService) for sending data to the server side:


public class NewsService {
  /**
   *  Login authentication 
   * @param name  The name 
   * @param password  password 
   * @return
   */
  public static boolean save(String name, String password){
    String path = "http://<span style="color: #ff0000;"><strong>192.168.1.104</strong></span>:8080/Register/ManageServlet"; 
    Map<String, String> student = new HashMap<String, String>();
    student.put("name", name);
    student.put("password", password);
    try {
      return SendGETRequest(path, student, "UTF-8");
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return false;
  }
  /**
   *  send GET request 
   * @param path   Request path 
   * @param student   Request parameters 
   * @return  Request successful or not 
   * @throws Exception
   */
  private static boolean SendGETRequest(String path, Map<String, String> student, String ecoding) throws Exception{
    // http://127.0.0.1:8080/Register/ManageServlet?name=1233&password=abc
    StringBuilder url = new StringBuilder(path);
    url.append("?");
    for(Map.Entry<String, String> map : student.entrySet()){
      url.append(map.getKey()).append("=");
      url.append(URLEncoder.encode(map.getValue(), ecoding));
      url.append("&");
    }
    url.deleteCharAt(url.length()-1);
    System.out.println(url);
    HttpsURLConnection conn = (HttpsURLConnection)new URL(url.toString()).openConnection();
    conn.setConnectTimeout(100000);
    conn.setRequestMethod("GET");
    if(conn.getResponseCode() == 200){
      return true;
    }
    return false;
  }
}

Because you need to connect to the network, 1 must configure the network permissions on ES31en. xml:


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

So far, Android has basically completed sending data to the server side, I hope this example will be helpful to your Android programming.


Related articles: