Three common data submission methods for "get" and "post" requests in Android

Source: Internet
Author: User

I. Submitting data using HttpURLConnection

"Get" request

Code:

String Path = "http://Address" Data 1 name = "+ Urlencoder.encode (data 1," utf-8 ") +" & Data 2 name = "+urlencoder.encode (data 2," Utf-8 ");

URL url = new URL (path);

HttpURLConnection conn = (httpurlconnection) url.openconnection ();

Here to set the request method to write in uppercase

Conn.setrequestmethod ("GET");

Conn.setconnecttimeout (5000);

int code = Conn.getresponsecode ();

if (code = = 200) {

InputStream is = Conn.getinputstream ();

Bytearrayoutputstream BAOs = new Bytearrayoutputstream ();
int len =-1;
byte[] buffer = new byte[1024];
while (len = is.read (buffer))! =-1) {
Baos.write (buffer, 0, Len);
}
Is.close ();

This will get the data returned by the server.
result = Baos.tostring ();

}

"POST" request

URL url = new URL (path);

HttpURLConnection conn = (httpurlconnection) url.openconnection ();

1 here to set the request method to write in uppercase

Conn.setrequestmethod ("POST");

Set Response duration

Conn.setconnecttimeout (5000);

2 Setting the type of HTTP request data is form type

Conn.setrequestproperty ("Content-type", "application/x-www-form-urlencoded");

String data = "1 name =" +urlencoder.encode (data 1, "utf-8") + "& Data 2 name =" + Urlencoder.encode (data 2, "Utf-8");

3 Set the length of data written to the server

Conn.setrequestproperty ("Content-length", String.valueof (Data.length ()));

4 Specify to write data to the server

Conn.setdooutput (TRUE);

5 Start writing data to the server

Conn.getoutputstream (). write (data.getbytes);

int code = Conn.getresponsecode ();

if (code = = 200) {

InputStream is = Conn.getinputstream ();

Bytearrayoutputstream BAOs = new Bytearrayoutputstream ();
int len =-1;
byte[] buffer = new byte[1024];
while (len = is.read (buffer))! =-1) {
Baos.write (buffer, 0, Len);
}
Is.close ();

Note: The return code here is "Utf-8" by default.

result = Baos.tostring ();

}

Two. Submit data using HttpClient

Note: The httpclient will be built into the Android SDK and can be used without adding any additional jar packages, copying and pasting files from the COM folder to the project.

Get mode:

String Path = "http://Address" Data 1 name = "+ Urlencoder.encode (data 1," utf-8 ") +" & Data 2 Name "+ Urlencoder.encode (data 2," Utf-8 ");

The process can be understood as a user browser action

1 Open Browser

HttpClient client = new Defaulthttpclient ();

2 Enter Address

HttpGet httpget = new HttpGet (path);

3 hit Enter

HttpResponse response = Client.execute (HttpGet);

Get Status Code

int code = Response.getstatusline (). Getstatuscode ();

Post mode:

String Path = "http://Address";

1 Open Browser

HttpClient client = new Defaulthttpclient ();

2 Enter Address

HttpPost HttpPost = new HttpPost (path);

list<namevaluepair> parameters = new arraylist<namevaluepair> ();

Parameters.Add (New Basicnamevaluepair ("Data 1 Name", data 1));

Parameters.Add (New Basicnamevaluepair ("Data 2 Name", data 1));

Httppost.setentity (new urlencodedformentity (Parameters, "Utf-8"));

3 hit Enter

HttpResponse response = Client.execute (HttpPost);

4 Getting the status code

int code = Response.getstatusline (). Getstatuscode ();

Three. Submitting data using the Asynchttpclient framework

The source code can be downloaded on the Internet

Copy the source code in the SRC directory of the downloaded source to the SRC directory of your project.

Get mode:

Request Path

String Path = "http://Address" Data 1 name = "+ urlencoder.encode (data 1) +" & Data 2 Name "+ Urlencoder.encode (data 2);

Asynchttpclient client = new Asynchttpclient ();

Client.get (path,new Asynchttpresponsehandler () {

public void onsuccess (int statuscode,header[]headers,byte[]responsebody) {

Request succeeded

New String (responsebody);//Data returned

}

public void onfailure (int statuscode,header[]headers,byte[]responsebody,throwable error) {

Request failed

String (responsebody);

}

});

Post mode:

String Path = "http://Address";

Asynchttpclient client = new Asynchttpclient ();

Requestparams params = new Requestparams ();

Params.put ("Data 1 Name", data 1);

Params.put ("Data 2 Name", data 2);

Client.post (path,params,new Asynchttpresponsehandler () {

public void onsuccess (int statuscode,header[]headers,byte[]responsebody) {

Request succeeded

New String (responsebody);//Data returned

}

public void onfailure (int statuscode,header[]headers,byte[]responsebody,throwable error) {

Request failed

String (responsebody);

}

});

The above is the basic code, write bad hope we do not take offense, but also hope to communicate with you a lot.

Three common data submission methods for "get" and "post" requests in Android

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.