Getting Started with Android: sending HTTP GET and POST requests

Source: Internet
Author: User

An explanation of HTTP requests has been explained in my blog:

http://blog.csdn.net/xiazdong/article/details/7215296

I have encapsulated a helper class for HTTP requests in http://blog.csdn.net/xiazdong/article/details/7725867, so it is easy to send get, post requests;

such as Httprequestutil.sendgetrequest (); Is to send a GET request;

First, the core code

HTTP GET Core Code:

(1) String value = Urlencoder.encode (String value, "UTF-8");

(2) String Path = "http://../path?key=" +value;

(3) URL url = new URL (path);//URL encoding is required for URLs here;

(4) HttpURLConnection con = (httpurlconnection) url.openconnection ();

(5) Con.setrequestmethod ("GET");

(6) Con.setdooutput (true);

(7) OutputStream out = Con.getoutputstream ();

(8) Out.write (BYTE[]BUF);

(9) Int code = Con.getresponsecode ();

HTTP POST Core Code:

(1) String value = Urlencoder.encode (String value, "UTF-8");

(2) Byte[]buf = ("key=" +value). GetBytes ("UTF-8");

(3) String Path = "Http://../path";

(4) URL url = new URL (path);//URL encoding is required for URLs here;

(5) HttpURLConnection con = (httpurlconnection) url.openconnection ();

(6) Con.setrequestmethod ("POST");

(7) Con.setdooutput (true);

(8) OutputStream out = Con.getoutputstream ();

(9) Out.write (BYTE[]BUF);

(ten) int code = Con.getresponsecode ();

Second, get and post garbled solution method

GET:  

Add in Doget:

String name = new String (Request.getparameter ("name"). GetBytes ("Iso-8859-1"), "UTF-8");

POST:  

Add in Dopost:

Request.setcharacterencoding ("UTF-8");

For more information, see my blog:

http://blog.csdn.net/xiazdong/article/details/7217022

Third, server-side code

[Java]View PlainCopy
  1. Package org.xiazdong.servlet;
  2. Import java.io.IOException;
  3. Import javax.servlet.ServletException;
  4. Import Javax.servlet.annotation.WebServlet;
  5. Import Javax.servlet.http.HttpServlet;
  6. Import Javax.servlet.http.HttpServletRequest;
  7. Import Javax.servlet.http.HttpServletResponse;
  8. @WebServlet ("/printservlet")
  9. Public class Printservlet extends HttpServlet {
  10. protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
  11. String name = new String (Request.getparameter ("name"). GetBytes ("iso-8859-1"),"UTF-8");
  12. String age = New String (Request.getparameter ("Age"). GetBytes ("iso-8859-1"),"UTF-8");
  13. System.out.println ("Name:" +name+"\ n Age:" +age);
  14. }
  15. protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
  16. Request.setcharacterencoding ("UTF-8");
  17. System.out.println ("Name:" +request.getparameter ("name") +"\ n Age:" +request.getparameter ("ages");
  18. }
  19. }


Four, the Android terminal code

Join in Androidmanifest.xml:

[HTML]View PlainCopy
    1. <uses-permission android:name="Android.permission.INTERNET"/>


Mainactivity.java

[Java]View PlainCopy
  1. Package org.xiazdong.network.submit;
  2. Import Java.io.OutputStream;
  3. Import java.net.HttpURLConnection;
  4. Import Java.net.URL;
  5. Import Java.net.URLEncoder;
  6. Import android.app.Activity;
  7. Import Android.os.Bundle;
  8. Import Android.view.View;
  9. Import Android.view.View.OnClickListener;
  10. Import Android.widget.Button;
  11. Import Android.widget.EditText;
  12. Import Android.widget.Toast;
  13. Public class Mainactivity extends Activity {
  14. private EditText name, age;
  15. private Button Getbutton, Postbutton;
  16. private Onclicklistener listener = New Onclicklistener () {
  17. @Override
  18. public void OnClick (View v) {
  19. try{
  20. if (Getbutton = = v) {
  21. /* 
  22. * Because it is a GET request, the request parameter needs to be added to the URL, and URL encoding is also required
  23. * URL = http://192.168.0.103:8080/Server/PrintServlet?name=%E6%88%91&age=20
  24. * URL encoding is required here because URL encoding is automatically made when the browser commits
  25. * */
  26. StringBuilder buf = new StringBuilder ("Http://192.168.0.103:8080/Server/PrintServlet");
  27. Buf.append ("?");
  28. Buf.append ("Name=" +urlencoder.encode (Name.gettext (). toString (),"UTF-8") +"&");
  29. Buf.append ("age=" +urlencoder.encode (Age.gettext (). toString (),"UTF-8"));
  30. URL url = new URL (buf.tostring ());
  31. HttpURLConnection conn = (httpurlconnection) url.openconnection ();
  32. Conn.setrequestmethod ("GET");
  33. if (conn.getresponsecode () = =){
  34. Toast.maketext (mainactivity.   This, "get submitted successfully", Toast.length_short). Show ();
  35. }
  36. Else Toast.maketext (mainactivity.   This, "get commit Failed", Toast.length_short). Show ();
  37. }
  38. if (Postbutton = = v) {
  39. /* 
  40. * If it is a POST request, the request parameter is placed in the request body,
  41. * NAME=%E6%88%91&AGE=12
  42. *
  43. * */
  44. StringBuilder buf = new StringBuilder ();
  45. Buf.append ("Name=" +urlencoder.encode (Name.gettext (). toString (),"UTF-8") +"&");
  46. Buf.append ("age=" +urlencoder.encode (Age.gettext (). toString (),"UTF-8"));
  47. byte[]data = buf.tostring (). GetBytes ("UTF-8");
  48. URL url = new URL ("Http://192.168.0.103:8080/Server/PrintServlet");
  49. HttpURLConnection conn = (httpurlconnection) url.openconnection ();
  50. Conn.setrequestmethod ("POST");
  51. Conn.setdooutput (true); //If you want to export, you must add this sentence
  52. OutputStream out = Conn.getoutputstream ();
  53. Out.write (data);
  54. if (conn.getresponsecode () = =){
  55. Toast.maketext (mainactivity.   This, "get submitted successfully", Toast.length_short). Show ();
  56. }
  57. Else Toast.maketext (mainactivity.   This, "get commit Failed", Toast.length_short). Show ();
  58. }
  59. }
  60. catch (Exception e) {
  61. }
  62. }
  63. };
  64. @Override
  65. public void OnCreate (Bundle savedinstancestate) {
  66. super.oncreate (savedinstancestate);
  67. Setcontentview (R.layout.main);
  68. Name = (EditText) This.findviewbyid (r.id.name);
  69. Age = (EditText) This.findviewbyid (r.id.age);
  70. Getbutton = (Button) This.findviewbyid (R.id.getbutton);
  71. Postbutton = (Button) This.findviewbyid (R.id.postbutton);
  72. Getbutton.setonclicklistener (listener);
  73. Postbutton.setonclicklistener (listener);
  74. }
  75. }


Getting Started with Android: sending HTTP GET and POST requests

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.