Android uses GET and POST methods to upload data to the server

Source: Internet
Author: User

The differences between the two are as follows:

The data uploaded by GET is usually very small and has low security performance. The data uploaded by POST is suitable for scenarios with large data volumes, complex data types, and high data security performance requirements.

GET and POST are generally used as follows:

1. Steps for passing data to the server using the GET Method

1. Use the Map set to obtain and process data
If (params! = Null &&! Params. isEmpty ()){
For (Map. Entry <String, String> entry: params. entrySet ()){

Sb. append (entry. getKey (). append ("= ");
Sb. append (URLEncoder. encode (entry. getValue (), encoding ));
Sb. append ("&");
}
Sb. deleteCharAt (sb. length ()-1 );

}
 
2. Create a StringBuilder object
Sb = new StringBuilder ()
3. Create an HttpURLConnection URL object, open the connection, and pass the server path
Connection = (HttpURLConnection) new URL (path). openConnection ();
4. Set timeout and Connection Methods

Connection. setConnectTimeout (5000 );
Connection. setRequestMethod ("GET ");


2. Steps for passing data to the server using the POST method
 

1. Use the Map set to obtain and process data
If (params! = Null &&! Params. isEmpty ()){
For (Map. Entry <String, String> entry: params. entrySet ()){

Sb. append (entry. getKey (). append ("= ");
Sb. append (URLEncoder. encode (entry. getValue (), encoding ));
Sb. append ("&");
}
Sb. deleteCharAt (sb. length ()-1 );

}
 
2. Create a StringBuilder object to obtain the data that POST is sent to the server.
Sb = new StringBuilder ()
Byte [] data = sb. toString (). getBytes ();
3. Create an HttpURLConnection URL object, open the connection, and pass the server path
Connection = (HttpURLConnection) new URL (path). openConnection ();
4. Set timeout and allow external connection data
Connection. setDoOutput (true );
5. Set the setRequestProperty attribute of the Connection

Connection. setRequestProperty ("Content-Type", "application/x-www-form-urlencoded ");
Connection. setRequestProperty ("Content-Length", data. length + "");
6. Get the connection output stream.
OutputStream = connection. getOutputStream ();
7. Write the obtained data to the output stream and refresh it.
OutputStream. write (data );
OutputStream. flush ();


 

3. The specific implementation process is as follows:
1. Use the GET method to upload data
The code in the doGet method on the server is as follows:

 

[Java] view plaincopyprint? Protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String name = request. getParameter ("name ");
String age = request. getParameter ("age ");
System. out. println ("-------- name:" + name );
System. out. println ("-------- age:" + age );

}

Protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String name = request. getParameter ("name ");
String age = request. getParameter ("age ");
System. out. println ("-------- name:" + name );
System. out. println ("-------- age:" + age );

}
The Code implemented on the client is as follows:

 

[Java] view plaincopyprint? Public class UserSerivce {
 
Public static boolean save (String getname, String getage) throws Exception {
 
String path = "http: // 10.254.1.62/WebForGETMethod/ServletForGetMethod ";
 
Map <String, String> params = new HashMap <String, String> ();
Params. put ("name", getname );
Params. put ("age", getage );
 
Return sendGETRequest (path, params, "UTF-8 ");
}
 
Private static boolean sendGETRequest (String path,
Map <String, String> params, String encoding) throws Exception {
 
StringBuilder sb = new StringBuilder (path );
If (params! = Null &&! Params. isEmpty ()){
Sb. append ("? ");
For (Map. Entry <String, String> entry: params. entrySet ()){
 
Sb. append (entry. getKey (). append ("= ");
Sb. append (URLEncoder. encode (entry. getValue (), encoding ));
Sb. append ("&");
}
Sb. deleteCharAt (sb. length ()-1 );
}
 
HttpURLConnection connection = (HttpURLConnection) new URL (
Sb. toString (). openConnection ();
Connection. setConnectTimeout (5000 );
Connection. setRequestMethod ("GET ");
If (connection. getResponseCode () = 200 ){
Return true;
}
 
Return false;
}
 
}

Public class UserSerivce {

Public static boolean save (String getname, String getage) throws Exception {

String path = "http: // 10.254.1.62/WebForGETMethod/ServletForGetMethod ";

Map <String, String> params = new HashMap <String, String> ();
Params. put ("name", getname );
Params. put ("age", getage );

Return sendGETRequest (path, params, "UTF-8 ");
}

Private static boolean sendGETRequest (String path,
Map <String, String> params, String encoding) throws Exception {

StringBuilder sb = new StringBuilder (path );
If (params! = Null &&! Params. isEmpty ()){
Sb. append ("? ");
For (Map. Entry <String, String> entry: params. entrySet ()){

Sb. append (entry. getKey (). append ("= ");
Sb. append (URLEncoder. encode (entry. getValue (), encoding ));
Sb. append ("&");
}
Sb. deleteCharAt (sb. length ()-1 );
}

HttpURLConnection connection = (HttpURLConnection) new URL (
Sb. toString (). openConnection ();
Connection. setConnectTimeout (5000 );
Connection. setRequestMethod ("GET ");
If (connection. getResponseCode () = 200 ){
Return true;
}

Return false;
}

}
Then, it is implemented on the android client interface.

 

[Java] view plaincopyprint? Public class GetDataToWebActivity extends Activity {
Private EditText name, age;
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. getdate );
Name = (EditText) findViewById (R. id. name );
Age = (EditText) findViewById (R. id. age );
}
Public void save (View v ){
String getname = name. getText (). toString ();
String getage = age. getText (). toString ();

Boolean result = false;
Try {
Result = UserSerivce. save (getname, getage );
} Catch (Exception e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}

If (result ){
Toast. makeText (this, "success", 1). show ();

} Else {
Toast. makeText (this, "failed", 1). show ();
}
}
}

Public class GetDataToWebActivity extends Activity {
Private EditText name, age;
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. getdate );
Name = (EditText) findViewById (R. id. name );
Age = (EditText) findViewById (R. id. age );
}
Public void save (View v ){
String getname = name. getText (). toString ();
String getage = age. getText (). toString ();

Boolean result = false;
Try {
Result = UserSerivce. save (getname, getage );
} Catch (Exception e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}

If (result ){
Toast. makeText (this, "success", 1). show ();

} Else {
Toast. makeText (this, "failed", 1). show ();
}
}
}

 

Related Article

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.