Android post get request

Source: Internet
Author: User
Tags apm html header

Android post get request

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:
  1. Namespace Home \ Controller;
  2. Use Think \ Controller;
  3. Class AndroidController extends Controller {
  4. Public function index ()
  5. {
  6. // Obtain the account password
  7. $ Id = I ('username ');
  8. $ Pwd = I ('Password ');
  9. $ User = M ('user ');
  10. // Query the database
  11. $ Data = $ User-> where ("NAME = '$ id' and password =' $ pwd'")-> find ();
  12. // Login successful
  13. If ($ data)
  14. {
  15. $ Response = array ('success' => true, 'msg '=> 'login successful ');
  16.  
  17. $ Response = json_encode ($ response );
  18. Echo $ response; // return the json format
  19. }
  20. // Login Failed
  21. Else
  22. {
  23. $ Response = array ('success' => false, 'msg '=> 'incorrect account or password ');
  24. $ Response = json_encode ($ response );
  25. Echo $ response; // return the json format
  26. }
  27. }
  28.  
  29. } 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.
    1. Package com. dream. apm;
    2.  
    3. Import android. app. Activity;
    4. Import android. content. pm. ActivityInfo;
    5. Import android. OS. Bundle;
    6. Import android. OS. Handler;
    7. Import android. OS. logoff;
    8. Import android. OS. Message;
    9. Import android. view. View;
    10. Import android. view. Window;
    11. Import android. view. WindowManager;
    12. Import android. widget. Button;
    13. Import android. widget. EditText;
    14. Import android. widget. LinearLayout;
    15. Import android. widget. Toast;
    16. Import org. json. JSONArray;
    17. Import org. json. JSONException;
    18. Import org. json. JSONObject;
    19.  
    20. Import java. io .*;
    21. Import java.net. HttpURLConnection;
    22. Import java.net. MalformedURLException;
    23. Import java.net. URL;
    24. Import java.net. URLEncoder;
    25.  
    26. Public class MyActivity extends Activity {
    27.  
    28. // Request address
    29. Private static String url = "http: // 10.0.2.2: 8080/think/index. php/Home/Android ";
    30. Public Button start;
    31.  
    32. Public EditText username, password;
    33.  
    34. Public URL http_url;
    35.  
    36. Public String data;
    37.  
    38. Public Handler handler;
    39.  
    40. @ Override
    41. Public void onCreate (Bundle savedInstanceState ){
    42. Super. onCreate (savedInstanceState );
    43. // Set full screen
    44. GetWindow (). setFlags (WindowManager. LayoutParams. FLAG_FULLSCREEN,
    45. WindowManager. LayoutParams. FLAG_FULLSCREEN );
    46. // Remove the application title
    47. This. requestWindowFeature (Window. FEATURE_NO_TITLE );
    48. // Set the portrait Screen
    49. SetRequestedOrientation (ActivityInfo. SCREEN_ORIENTATION_PORTRAIT );
    50. SetContentView (R. layout. main );
    51.  
    52. Start = (Button) findViewById (R. id. start_one );
    53. Username = (EditText) findViewById (R. id. username );
    54. Password = (EditText) findViewById (R. id. password );
    55. // Message processor
    56.  
    57. Handler = new Handler (Looper. getMainLooper ())
    58. {
    59. @ Override
    60. Public void handleMessage (Message msg)
    61. {
    62. Super. handleMessage (msg );
    63. Switch (msg. what)
    64. {
    65. // Login successful
    66. Case 1:
    67. Toast. makeText (MyActivity. this, msg. getData (). getString ("msg "),
    68. Toast. LENGTH_SHORT). show ();
    69. Break;
    70. // Login Failed
    71. Case 2:
    72. Toast. makeText (MyActivity. this, msg. getData (). getString ("msg "),
    73. Toast. LENGTH_SHORT). show ();
    74. Break;
    75.  
    76. }
    77. }
    78. };
    79.  
    80. Start. setOnClickListener (new View. OnClickListener (){
    81. @ Override
    82. Public void onClick (View v ){
    83. // Whether to enter the account password
    84. If (username. getText (). toString (). length ()> 0 & password. getText (). toString (). length ()> 0 ){
    85. // The Sub-thread can obtain the UI value and cannot be changed.
    86. New Thread (new Runnable (){
    87. @ Override
    88. Public void run (){
    89. Try {
    90. Http_url = new URL (url );
    91. If (http_url! = Null)
    92. {
    93. // Open an HttpURLConnection connection
    94. HttpURLConnection conn = (HttpURLConnection) http_url.openConnection ();
    95. Conn. setConnectTimeout (5*1000); // sets the connection timeout.
    96. Conn. setRequestMethod ("POST"); // initiate a request in get Mode
    97. // Allow input and output streams
    98. Conn. setDoInput (true );
    99. Conn. setDoOutput (true );
    100. Conn. setUseCaches (false); // The cache cannot be used in Post mode.
    101. // Obtain the account password
    102. String params = "username =" + username. getText (). toString ()
    103. + "& Password =" + password. getText (). toString ();
    104. // Set the Request body type to text
    105. Conn. setRequestProperty ("Content-Type", "application/x-www-form-urlencoded ");
    106. // Set the length of the Request body, in bytes.
    107. Conn. setRequestProperty ("Content-Length", String. valueOf (params. getBytes (). length ));
    108. // Send the post Parameter
    109. BufferedWriter bw = new BufferedWriter (new OutputStreamWriter (conn. getOutputStream ()));
    110. Bw. write (params );
    111. Bw. close ();
    112. // Receives Server Response
    113. If (conn. getResponseCode () = 200 ){
    114. InputStream is = conn. getInputStream (); // gets the input stream returned by the network.
    115. BufferedReader buf = new BufferedReader (new InputStreamReader (is); // converts it to a character buffer stream
    116. Data = buf. readLine ();
    117. Buf. close (); is. close ();
    118. // Determine the logon result
    119. Analyze (data );
    120. }
    121. }
    122. } Catch (Exception e ){
    123. E. printStackTrace ();
    124. }
    125. }
    126. }). Start ();
    127. }
    128. Else
    129. {
    130. Toast. makeText (MyActivity. this, "enter your account and password ",
    131. Toast. LENGTH_SHORT). show ();
    132. }
    133. }
    134. });
    135. }
    136.  
    137. Public void analyze (String data)
    138. {
    139. System. out. println (data );
    140. Try {
    141. JSONObject json_data = new JSONObject (data );
    142. Boolean state = json_data.getBoolean ("success ");
    143. String msg = json_data.getString ("msg ");
    144. // Login successful
    145. If (state)
    146. {
    147. // Send a message
    148. Message message = new Message ();
    149. Message. what = 1;
    150. Bundle temp = new Bundle ();
    151. Temp. putString ("msg", msg );
    152. Message. setData (temp );
    153. Handler. sendMessage (message );
    154.  
    155. }
    156. // Login Failed
    157. Else
    158. {
    159. Message message = new Message ();
    160. Message. what = 2;
    161. Bundle temp = new Bundle ();
    162. Temp. putString ("msg", msg );
    163. Message. setData (temp );
    164. Handler. sendMessage (message );
    165. }
    166. } Catch (JSONException e ){
    167. E. printStackTrace ();
    168. }
    169. }
    170. } Copy the Code 2. Use the GET request method to implement personnel Login
      1. Package com. dream. apm;
      2.  
      3. Import android. app. Activity;
      4. Import android. content. pm. ActivityInfo;
      5. Import android. OS. Bundle;
      6. Import android. OS. Handler;
      7. Import android. OS. logoff;
      8. Import android. OS. Message;
      9. Import android. view. View;
      10. Import android. view. Window;
      11. Import android. view. WindowManager;
      12. Import android. widget. Button;
      13. Import android. widget. EditText;
      14. Import android. widget. LinearLayout;
      15. Import android. widget. Toast;
      16. Import org. json. JSONArray;
      17. Import org. json. JSONException;
      18. Import org. json. JSONObject;
      19.  
      20. Import java. io .*;
      21. Import java.net. HttpURLConnection;
      22. Import java.net. MalformedURLException;
      23. Import java.net. URL;
      24. Import java.net. URLEncoder;
      25.  
      26. Public class MyActivity extends Activity {
      27.  
      28. Public Button start;
      29.  
      30. Public EditText username, password;
      31.  
      32. Public URL http_url;
      33.  
      34. Public String data;
      35.  
      36. Public Handler handler;
      37.  
      38. @ Override
      39. Public void onCreate (Bundle savedInstanceState ){
      40. Super. onCreate (savedInstanceState );
      41. // Set full screen
      42. GetWindow (). setFlags (WindowManager. LayoutParams. FLAG_FULLSCREEN,
      43. WindowManager. LayoutParams. FLAG_FULLSCREEN );
      44. // Remove the application title
      45. This. requestWindowFeature (Window. FEATURE_NO_TITLE );
      46. // Set the portrait Screen
      47. SetRequestedOrientation (ActivityInfo. SCREEN_ORIENTATION_PORTRAIT );
      48. SetContentView (R. layout. main );
      49.  
      50. Start = (Button) findViewById (R. id. start_one );
      51. Username = (EditText) findViewById (R. id. username );
      52. Password = (EditText) findViewById (R. id. password );
      53. // Message processor
      54.  
      55. Handler = new Handler (Looper. getMainLooper ())
      56. {
      57. @ Override
      58. Public void handleMessage (Message msg)
      59. {
      60. Super. handleMessage (msg );
      61. Switch (msg. what)
      62. {
      63. // Login successful
      64. Case 1:
      65. Toast. makeText (MyActivity. this, msg. getData (). getString ("msg "),
      66. Toast. LENGTH_SHORT). show ();
      67. Break;
      68. // Login Failed
      69. Case 2:
      70. Toast. makeText (MyActivity. this, msg. getData (). getString ("msg "),
      71. Toast. LENGTH_SHORT). show ();
      72. Break;
      73.  
      74. }
      75. }
      76. };
      77.  
      78. Start. setOnClickListener (new View. OnClickListener (){
      79. @ Override
      80. Public void onClick (View v ){
      81. // Whether to enter the account password
      82. If (username. getText (). toString (). length ()> 0 & password. getText (). toString (). length ()> 0 ){
      83. // The Sub-thread can obtain the UI value and cannot be changed.
      84. New Thread (new Runnable (){
      85. @ Override
      86. Public void run (){
      87. Try {
      88. // Request address --
      89. String url = "http: // 10.0.2.2: 8080/think/index. php/Home/Android? "+" Username = "+ URLEncoder. encode (username. getText (). toString ()," UTF-8 ")
      90. + "& Password =" + URLEncoder. encode (password. getText (). toString (), "UTF-8 ");
      91. Http_url = new URL (url );
      92. If (http_url! = Null)
      93. {
      94. // Open an HttpURLConnection connection
      95. HttpURLConnection conn = (HttpURLConnection) http_url.openConnection ();
      96. Conn. setConnectTimeout (5*1000); // sets the connection timeout.
      97. Conn. setRequestMethod ("GET"); // initiate a request in get Mode
      98. // Allow input stream
      99. Conn. setDoInput (true );
      100. // Receives Server Response
      101. If (conn. getResponseCode () = 200 ){
      102. InputStream is = conn. getInputStream (); // gets the input stream returned by the network.
      103. BufferedReader buf = new BufferedReader (new InputStreamReader (is); // converts it to a character buffer stream
      104. Data = buf. readLine ();
      105. Buf. close (); is. close ();
      106. // Determine the logon result
      107. Analyze (data );
      108. }
      109. }
      110. } Catch (Exception e ){
      111. E. printStackTrace ();
      112. }
      113. }
      114. }). Start ();
      115. }
      116. Else
      117. {
      118. Toast. makeText (MyActivity. this, "enter your account and password ",
      119. Toast. LENGTH_SHORT). show ();
      120. }
      121. }
      122. });
      123. }
      124.  
      125. Public void analyze (String data)
      126. {
      127. System. out. println (data );
      128. Try {
      129. JSONObject json_data = new JSONObject (data );
      130. Boolean state = json_data.getBoolean ("success ");
      131. String msg = json_data.getString ("msg ");
      132. // Login successful
      133. If (state)
      134. {
      135. // Send a message
      136. Message message = new Message ();
      137. Message. what = 1;
      138. Bundle temp = new Bundle ();
      139. Temp. putString ("msg", msg );
      140. Message. setData (temp );
      141. Handler. sendMessage (message );
      142.  
      143. }
      144. // Login Failed
      145. Else
      146. {
      147. Message message = new Message ();
      148. Message. what = 2;
      149. Bundle temp = new Bundle ();
      150. Temp. putString ("msg", msg );
      151. Message. setData (temp );
      152. Handler. sendMessage (message );
      153. }
      154. } Catch (JSONException e ){
      155. E. printStackTrace ();
      156. }
      157. }
      158. } Copy the code running result:



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.