Three POST and GET submission methods: postget submission

Source: Internet
Author: User
Tags response code

Three POST and GET submission methods: postget submission

There are two ways to submit data to the server: post and get. There are three main differences between the two: security, length restrictions, and data structure. The get request is less secure. The data length is restricted by the address bar of the browser and there is no method body. Both are important data submission methods. This section briefly introduces three post and get submission methods. No matter which method implements post and get, the get access path must carry data, while the post submission puts the data in the method body.

Common Methods for get/post submission:

Data transmission is performed in strict accordance with the Http protocol. In the android development environment, because the main thread cannot access the network, you need to open a subthread to submit data to the server. To observe data more intuitively, the server feedback information can be displayed on the Program Screen. The Hnndler agent must be introduced because the sub-thread cannot change the UI. The basic step for get/post submission is to obtain the URL path, get the Http connection according to the path, and use the HttpURLConnection object to set the relevant http configuration information, submission method, and get the feedback code. When the response code is 200, the request is submitted successfully. You can use HttpURLConnection to obtain feedback in the form of a stream.

Common GRT submission method:

Public void load (View view) {final String qq = et_qq.getText (). toString (). trim (); final String pwd = et_pwd.getText (). toString (). trim (); if (TextUtils. isEmpty (qq) | TextUtils. isEmpty (pwd) {Toast. makeText (MainActivity. this, "QQ number or password is blank", 0 ). show (); return;} final String path = "http: // 192.168.1.114: 8080/qqload? Qq = "+ qq +" & pwd = "+ pwd; new Thread () {public void run () {try {URL url = new URL (path ); httpURLConnection conn = (HttpURLConnection) url. openConnection (); conn. setRequestMethod ("GET"); conn. setReadTimeout (5000); int code = conn. getResponseCode (); if (code = 200) {InputStream is = conn. getInputStream (); String result = StreamTools. readStream (is); Message msg = Message. obtain (); msg. what = SUCCESS; msg. obj = result; handler. sendMessage (msg);} else {Message msg = Message. obtain (); msg. what = ERROR1; handler. sendMessage (msg) ;}} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace (); Message msg = Message. obtain (); msg. what = ERROR2; handler. sendMessage (msg );}}}. start ();}

  

Common POST submission method:

Public void load (View view) {final String qq = et_qq.getText (). toString (). trim (); final String pwd = et_pwd.getText (). toString (). trim (); if (TextUtils. isEmpty (qq) | TextUtils. isEmpty (pwd) {Toast. makeText (MainActivity. this, "QQ number or password is blank", 0 ). show (); return;} final String path = "http: // 192.168.1.114: 8080/qqload"; new Thread () {public void run () {try {URL url = new URL (path); HttpURLConnection conn = (HttpURLConnection) url. openConnection (); conn. setRequestMethod ("POST"); conn. setreadtimeouts (5000); conn. setRequestProperty ("Content-Type", "application/x-www-form-urlencoded"); String data = "qq =" + URLEncoder. encode (qq, "UTF-8") + "& pwd =" + URLEncoder. encode (pwd, "UTF-8"); conn. setRequestProperty ("Content-Length", String. valueOf (data. length (); conn. setDoOutput (true); conn. getOutputStream (). write (data. getBytes (); int code = conn. getResponseCode (); if (code = 200) {InputStream is = conn. getInputStream (); String result = StreamTools. readStream (is); Message msg = Message. obtain (); msg. what = SUCCESS; msg. obj = result; handler. sendMessage (msg);} else {Message msg = Message. obtain (); msg. what = ERROR1; handler. sendMessage (msg) ;}} catch (Exception e) {// TODO Auto-generated catch block e. printStackTrace (); Message msg = Message. obtain (); msg. what = ERROR2; handler. sendMessage (msg );}}}. start ();}

 

To use httpclien to implement get/post submission, you only need to perform the following steps:

1. Create an HttpClient object to enable the browser.

HttpClient client = new DefaultHttpClient ();

2. Enter the address or data, use HttpGet () or HttpPost (), and input the path to be accessed to obtain the HttpGet or HttpPost object.

HttpGet httpGet = new HttpGet (path );

3. Send the obtained HttpGet or HttpPost object to the server and press enter to obtain the HttpResponse object.

HttpResponse response = client.exe cute (httpGet );

4. Get the status code in the status line of the HttpResponse object and determine the status code.

Int code = response. getStatusLine (). getStatusCode ();

5. Use the HttpResponse object to get the corresponding content and store it to the stream object. Finally, convert the obtained Stream object to a string for display.

InputStream is = response. getEntity (). getContent ();

Note that a value must be transferred when a post request is used. Therefore, an additional step is required. Specifically, a list set is created first. The generic type of the set is represented by NameValuePair, which stores the data to be transmitted in the form of a key-value pair. Add the data to be submitted to the collection. Finally, use the HttpPost object to save the set to the Request body.

Use HttpClient to implement GET submission:

Public void load (View view) {final String qq = et_qq.getText (). toString (). trim (); final String pwd = et_pwd.getText (). toString (). trim (); if (TextUtils. isEmpty (qq) | TextUtils. isEmpty (pwd) {Toast. makeText (MainActivity. this, "QQ number or password is blank", 0 ). show (); return;} final String path = "http: // 192.168.1.114: 8080/qqload? Qq = "+ qq +" & pwd = "+ pwd; new Thread () {public void run () {try {HttpClient client = new DefaultHttpClient (); httpGet httpget = new HttpGet (path); HttpResponse response = client.exe cute (httpget); int code = response. getStatusLine (). getStatusCode (); if (code == 200) {InputStream is = response. getEntity (). getContent (); String result = StreamTools. readStream (is); Message msg = Message. obtain (); msg. what = SUCCESS; msg. obj = result; handler. sendMessage (msg);} else {Message msg = Message. obtain (); msg. what = ERROR1; handler. sendMessage (msg) ;}} catch (Exception e) {// TODO Auto-generated catch block e. printStackTrace (); Message msg = Message. obtain (); msg. what = ERROR2; handler. sendMessage (msg );}}}. start ();}

 

Use HttpClient to implement POST submission:

Public void load (View view) {final String qq = et_qq.getText (). toString (). trim (); final String pwd = et_pwd.getText (). toString (). trim (); if (TextUtils. isEmpty (qq) | TextUtils. isEmpty (pwd) {Toast. makeText (MainActivity. this, "QQ number or password is blank", 0 ). show (); return;} final String path = "http: // 192.168.1.114: 8080/qqload"; new Thread () {public void run () {try {HttpClient client = new DefaultHttpClient (); HttpPost httppost = new HttpPost (path); List <NameValuePair> parameter = new ArrayList (); parameter. add (new BasicNameValuePair ("qq", qq); parameter. add (new BasicNameValuePair ("pwd", pwd); httppost. setEntity (new UrlEncodedFormEntity (parameter, "UTF-8"); HttpResponse response = client.exe cute (httppost); int code = response. getStatusLine (). getStatusCode (); if (code == 200) {InputStream is = response. getEntity (). getContent (); String result = StreamTools. readStream (is); Message msg = Message. obtain (); msg. what = SUCCESS; msg. obj = result; handler. sendMessage (msg);} else {Message msg = Message. obtain (); msg. what = ERROR1; handler. sendMessage (msg) ;}} catch (Exception e) {// TODO Auto-generated catch block e. printStackTrace (); Message msg = Message. obtain (); msg. what = ERROR2; handler. sendMessage (msg );}}}. start ();}

 

Use the open-source framework to implement get/post submission:

You do not need to open the sub-thread to implement get/post submission using the framework. Submitting get/post directly in the main thread greatly reduces the workload. However, you need to import the package before the operation. Then, create an AsyncHttpClient object, send the request using the post and get methods of the AsyncHttpClient object, and obtain the relevant information in the AsyncHttpResponseHandler () object. Similarly, if it is a post request, the value still needs to be passed. Here, you can use the RequestParams object to add the value to be passed.

Add a jar package to the file:

Use the open-source framework to implement GET submission:

Public void load (View view) {final String qq = et_qq.getText (). toString (). trim (); final String pwd = et_pwd.getText (). toString (). trim (); if (TextUtils. isEmpty (qq) | TextUtils. isEmpty (pwd) {Toast. makeText (MainActivity. this, "QQ number or password is blank", 0 ). show (); return;} final String path = "http: // 192.168.1.114: 8080/qqload? Qq = "+ qq +" & pwd = "+ pwd; AsyncHttpClient client = new AsyncHttpClient (); client. get (path, new AsyncHttpResponseHandler () {@ Override public void onSuccess (int statusCode, Header [] headers, byte [] responseBody) {// TODO Auto-generated method stub TV _result.setText (new String (responseBody);} @ Override public void onFailure (int statusCode, Header [] headers, byte [] responseBody, throwable error) {// TODO Auto-generated method stub TV _result.setText ("error cause:" + new String (responseBody ));}});}

 

Use an open-source framework to implement POST requests:

Public void load (View view) {final String qq = et_qq.getText (). toString (). trim (); final String pwd = et_pwd.getText (). toString (). trim (); if (TextUtils. isEmpty (qq) | TextUtils. isEmpty (pwd) {Toast. makeText (MainActivity. this, "QQ number or password is blank", 0 ). show (); return;} final String path = "http: // 192.168.1.114: 8080/qqload"; AsyncHttpClient client = new AsyncHttpClient (); requestParams params = new RequestParams (); params. add ("qq", qq); params. add ("pwd", pwd); client. post (path, params, new AsyncHttpResponseHandler () {@ Override public void onSuccess (int statusCode, Header [] headers, byte [] responseBody) {// TODO Auto-generated method stub TV _result.setText (new String (responseBody);} @ Override public void onFailure (int statusCode, Header [] headers, byte [] responseBody, throwable error) {// TODO Auto-generated method stub TV _result.setText (new String (responseBody ));}});}

Any of the above methods can achieve the function of submitting data from the Android mobile phone end to the server end, the server side for judgment, and return the corresponding results. The three methods have their own advantages and disadvantages, and achieve the same effect. In actual use, you can choose according to your own needs.

 

 

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.