Android applications often interact with the server, which requires the mobile client to send network requests. The following describes two commonly used network request methods: POST and GET. First, we need to distinguish POST from GET requests. 1. GET is to GET data from the server, and POST is to send data to the server. 2. GET is to add the parameter data queue to the URL referred to by the ACTION attribute of the submission form. The values correspond to each field in the form one by one and can be seen in the URL. POST uses the HTTP post mechanism to place fields in the form and their content in the html header and send them to the URL address referred to by the ACTION attribute. The user cannot see this process 3. data submitted in GET mode can only be 1024 bytes at most. Theoretically, there is no limit on POST and a large amount of data can be transferred. 4. Low GET security and high POST security. However, the execution efficiency is better than the POST method.
Next we will use the Post and GET methods to implement the login of Android app personnel. First we will build a server. Here I will use the WAMP ENVIRONMENT AND THE ThinkPHP framework. The detailed server construction will not be mentioned. The main response code is provided:
-
- Namespace Home \ Controller;
- Use Think \ Controller;
- Class AndroidController extends Controller {
- Public function index ()
- {
- // Obtain the account password
- $ Id = I ('username ');
- $ Pwd = I ('Password ');
- $ User = M ('user ');
- // Query the database
- $ Data = $ User-> where ("NAME = '$ id' and password =' $ pwd'")-> find ();
- // Login successful
- If ($ data)
- {
- $ Response = array ('success' => true, 'msg '=> 'login successful ');
-
- $ Response = json_encode ($ response );
- Echo $ response; // return the json format
- }
- // Login Failed
- Else
- {
- $ Response = array ('success' => false, 'msg '=> 'incorrect account or password ');
- $ Response = json_encode ($ response );
- Echo $ response; // return the json format
- }
- }
-
- } Copy the code and remember to add network permissions. Android Network requests mainly use the HttpURLConnection class in the java.net package. The data interaction format between the server and the Android client is json 1. POST requests are used for personnel login.
- Package com. dream. apm;
-
- Import android. app. Activity;
- Import android. content. pm. ActivityInfo;
- Import android. OS. Bundle;
- Import android. OS. Handler;
- Import android. OS. logoff;
- Import android. OS. Message;
- Import android. view. View;
- Import android. view. Window;
- Import android. view. WindowManager;
- Import android. widget. Button;
- Import android. widget. EditText;
- Import android. widget. LinearLayout;
- Import android. widget. Toast;
- Import org. json. JSONArray;
- Import org. json. JSONException;
- Import org. json. JSONObject;
-
- Import java. io .*;
- Import java.net. HttpURLConnection;
- Import java.net. MalformedURLException;
- Import java.net. URL;
- Import java.net. URLEncoder;
-
- Public class MyActivity extends Activity {
-
- // Request address
- Private static String url = "http: // 10.0.2.2: 8080/think/index. php/Home/Android ";
- Public Button start;
-
- Public EditText username, password;
-
- Public URL http_url;
-
- Public String data;
-
- Public Handler handler;
-
- @ Override
- Public void onCreate (Bundle savedInstanceState ){
- Super. onCreate (savedInstanceState );
- // Set full screen
- GetWindow (). setFlags (WindowManager. LayoutParams. FLAG_FULLSCREEN,
- WindowManager. LayoutParams. FLAG_FULLSCREEN );
- // Remove the application title
- This. requestWindowFeature (Window. FEATURE_NO_TITLE );
- // Set the portrait Screen
- SetRequestedOrientation (ActivityInfo. SCREEN_ORIENTATION_PORTRAIT );
- SetContentView (R. layout. main );
-
- Start = (Button) findViewById (R. id. start_one );
- Username = (EditText) findViewById (R. id. username );
- Password = (EditText) findViewById (R. id. password );
- // Message processor
-
- Handler = new Handler (Looper. getMainLooper ())
- {
- @ Override
- Public void handleMessage (Message msg)
- {
- Super. handleMessage (msg );
- Switch (msg. what)
- {
- // Login successful
- Case 1:
- Toast. makeText (MyActivity. this, msg. getData (). getString ("msg "),
- Toast. LENGTH_SHORT). show ();
- Break;
- // Login Failed
- Case 2:
- Toast. makeText (MyActivity. this, msg. getData (). getString ("msg "),
- Toast. LENGTH_SHORT). show ();
- Break;
-
- }
- }
- };
-
- Start. setOnClickListener (new View. OnClickListener (){
- @ Override
- Public void onClick (View v ){
- // Whether to enter the account password
- If (username. getText (). toString (). length ()> 0 & password. getText (). toString (). length ()> 0 ){
- // The Sub-thread can obtain the UI value and cannot be changed.
- New Thread (new Runnable (){
- @ Override
- Public void run (){
- Try {
- Http_url = new URL (url );
- If (http_url! = Null)
- {
- // Open an HttpURLConnection connection
- HttpURLConnection conn = (HttpURLConnection) http_url.openConnection ();
- Conn. setConnectTimeout (5*1000); // sets the connection timeout.
- Conn. setRequestMethod ("POST"); // initiate a request in get Mode
- // Allow input and output streams
- Conn. setDoInput (true );
- Conn. setDoOutput (true );
- Conn. setUseCaches (false); // The cache cannot be used in Post mode.
- // Obtain the account password
- String params = "username =" + username. getText (). toString ()
- + "& Password =" + password. getText (). toString ();
- // Set the Request body type to text
- Conn. setRequestProperty ("Content-Type", "application/x-www-form-urlencoded ");
- // Set the length of the Request body, in bytes.
- Conn. setRequestProperty ("Content-Length", String. valueOf (params. getBytes (). length ));
- // Send the post Parameter
- BufferedWriter bw = new BufferedWriter (new OutputStreamWriter (conn. getOutputStream ()));
- Bw. write (params );
- Bw. close ();
- // Receives Server Response
- If (conn. getResponseCode () = 200 ){
- InputStream is = conn. getInputStream (); // gets the input stream returned by the network.
- BufferedReader buf = new BufferedReader (new InputStreamReader (is); // converts it to a character buffer stream
- Data = buf. readLine ();
- Buf. close (); is. close ();
- // Determine the logon result
- Analyze (data );
- }
- }
- } Catch (Exception e ){
- E. printStackTrace ();
- }
- }
- }). Start ();
- }
- Else
- {
- Toast. makeText (MyActivity. this, "enter your account and password ",
- Toast. LENGTH_SHORT). show ();
- }
- }
- });
- }
-
- Public void analyze (String data)
- {
- System. out. println (data );
- Try {
- JSONObject json_data = new JSONObject (data );
- Boolean state = json_data.getBoolean ("success ");
- String msg = json_data.getString ("msg ");
- // Login successful
- If (state)
- {
- // Send a message
- Message message = new Message ();
- Message. what = 1;
- Bundle temp = new Bundle ();
- Temp. putString ("msg", msg );
- Message. setData (temp );
- Handler. sendMessage (message );
-
- }
- // Login Failed
- Else
- {
- Message message = new Message ();
- Message. what = 2;
- Bundle temp = new Bundle ();
- Temp. putString ("msg", msg );
- Message. setData (temp );
- Handler. sendMessage (message );
- }
- } Catch (JSONException e ){
- E. printStackTrace ();
- }
- }
- } Copy the Code 2. Use the GET request method to implement personnel Login
- Package com. dream. apm;
-
- Import android. app. Activity;
- Import android. content. pm. ActivityInfo;
- Import android. OS. Bundle;
- Import android. OS. Handler;
- Import android. OS. logoff;
- Import android. OS. Message;
- Import android. view. View;
- Import android. view. Window;
- Import android. view. WindowManager;
- Import android. widget. Button;
- Import android. widget. EditText;
- Import android. widget. LinearLayout;
- Import android. widget. Toast;
- Import org. json. JSONArray;
- Import org. json. JSONException;
- Import org. json. JSONObject;
-
- Import java. io .*;
- Import java.net. HttpURLConnection;
- Import java.net. MalformedURLException;
- Import java.net. URL;
- Import java.net. URLEncoder;
-
- Public class MyActivity extends Activity {
-
- Public Button start;
-
- Public EditText username, password;
-
- Public URL http_url;
-
- Public String data;
-
- Public Handler handler;
-
- @ Override
- Public void onCreate (Bundle savedInstanceState ){
- Super. onCreate (savedInstanceState );
- // Set full screen
- GetWindow (). setFlags (WindowManager. LayoutParams. FLAG_FULLSCREEN,
- WindowManager. LayoutParams. FLAG_FULLSCREEN );
- // Remove the application title
- This. requestWindowFeature (Window. FEATURE_NO_TITLE );
- // Set the portrait Screen
- SetRequestedOrientation (ActivityInfo. SCREEN_ORIENTATION_PORTRAIT );
- SetContentView (R. layout. main );
-
- Start = (Button) findViewById (R. id. start_one );
- Username = (EditText) findViewById (R. id. username );
- Password = (EditText) findViewById (R. id. password );
- // Message processor
-
- Handler = new Handler (Looper. getMainLooper ())
- {
- @ Override
- Public void handleMessage (Message msg)
- {
- Super. handleMessage (msg );
- Switch (msg. what)
- {
- // Login successful
- Case 1:
- Toast. makeText (MyActivity. this, msg. getData (). getString ("msg "),
- Toast. LENGTH_SHORT). show ();
- Break;
- // Login Failed
- Case 2:
- Toast. makeText (MyActivity. this, msg. getData (). getString ("msg "),
- Toast. LENGTH_SHORT). show ();
- Break;
-
- }
- }
- };
-
- Start. setOnClickListener (new View. OnClickListener (){
- @ Override
- Public void onClick (View v ){
- // Whether to enter the account password
- If (username. getText (). toString (). length ()> 0 & password. getText (). toString (). length ()> 0 ){
- // The Sub-thread can obtain the UI value and cannot be changed.
- New Thread (new Runnable (){
- @ Override
- Public void run (){
- Try {
- // Request address --
- String url = "http: // 10.0.2.2: 8080/think/index. php/Home/Android? "+" Username = "+ URLEncoder. encode (username. getText (). toString ()," UTF-8 ")
- + "& Password =" + URLEncoder. encode (password. getText (). toString (), "UTF-8 ");
- Http_url = new URL (url );
- If (http_url! = Null)
- {
- // Open an HttpURLConnection connection
- HttpURLConnection conn = (HttpURLConnection) http_url.openConnection ();
- Conn. setConnectTimeout (5*1000); // sets the connection timeout.
- Conn. setRequestMethod ("GET"); // initiate a request in get Mode
- // Allow input stream
- Conn. setDoInput (true );
- // Receives Server Response
- If (conn. getResponseCode () = 200 ){
- InputStream is = conn. getInputStream (); // gets the input stream returned by the network.
- BufferedReader buf = new BufferedReader (new InputStreamReader (is); // converts it to a character buffer stream
- Data = buf. readLine ();
- Buf. close (); is. close ();
- // Determine the logon result
- Analyze (data );
- }
- }
- } Catch (Exception e ){
- E. printStackTrace ();
- }
- }
- }). Start ();
- }
- Else
- {
- Toast. makeText (MyActivity. this, "enter your account and password ",
- Toast. LENGTH_SHORT). show ();
- }
- }
- });
- }
-
- Public void analyze (String data)
- {
- System. out. println (data );
- Try {
- JSONObject json_data = new JSONObject (data );
- Boolean state = json_data.getBoolean ("success ");
- String msg = json_data.getString ("msg ");
- // Login successful
- If (state)
- {
- // Send a message
- Message message = new Message ();
- Message. what = 1;
- Bundle temp = new Bundle ();
- Temp. putString ("msg", msg );
- Message. setData (temp );
- Handler. sendMessage (message );
-
- }
- // Login Failed
- Else
- {
- Message message = new Message ();
- Message. what = 2;
- Bundle temp = new Bundle ();
- Temp. putString ("msg", msg );
- Message. setData (temp );
- Handler. sendMessage (message );
- }
- } Catch (JSONException e ){
- E. printStackTrace ();
- }
- }
- } Copy the code running result:
|