Three sets of API implementations send a GET, POST request to the server

Source: Internet
Author: User
Tags throwable

1. Use the URL class implementation to send the request to the server:1.1. Get method Request:

Note: The Get method request here, if the request parameter with the past has Chinese characters, then need to do
URL encoding, otherwise it will not be carried over.
number=%e7%90%83%e7%90%83
Number= Urlencoder.encode (number, "UTF-8");
Path = path+ "? number=" +number+ "&password=" +password;
URL url = new URL (path);

Get mode: The service side to solve garbled, need to manually decode

String Encodevalue = Urlencoder. encode (Number, "iso8859-1");

Number = Urldecoder. Decode (Encodevalue, "UTF-8");

1.2. Post Method Request:

url url = new URL (path);

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

Conn.setconnecttimeout (the);

//Use post mode
Conn.setrequestmethod ("POST");

//number=%e5%b0%8f%e9%8a%ae&password=sdfds
Chinese data also needs URL encoding when//post request

//The Chinese value of number is required for URL encoding
Number = Urlencoder.encode (number, "UTF-8");
System.out.println (number);
String params = "number=" +number+ "&password=" +password;

//Set the required headers for the requested information
conn.setrequestproperty ("Content-type", "application/x-www-form-urlencoded");
conn.setrequestproperty ("Content-length", params.length () + "");

//The parameter params is written to the server in the form of a stream

//plus a flag indicating that you want to write data to the server
Conn.setdooutput (true);
Conn.getoutputstream (). Write (Params.getbytes ());

int code = Conn.getresponsecode ();

Post mode, only one line of code is needed

Post is garbled//This code is only valid for post, because the decoding of the data in the requested body is used to encode the set

request. setcharacterencoding ("Utf-8");

2. Apache's object-oriented API implementation sends the request:2.1:get Way:

This set of APIs, Google engineers have been integrated into Android. So you can just take it with you.

//http://188.188.4.100:8080/day06_android/login?number=110&password=123


Number =urlencoder.encode (number, "UTF-8");
path = path+ "? number=" +number+ "&password=" +password;

//The equivalent of opening a browser client
HttpClient client = new Defaulthttpclient ();

Request for//get mode
HttpGet get = new HttpGet (path);

//Received Response object
HttpResponse response = Client.execute (get);

//Get the Status line object, and then get the status code in the status line
int code = response.getstatusline (). Getstatuscode ();

if (code==200) {

//Get the response body, get the data of the stream in the response body
//The next code is the same as before
InputStream in = Response.getentity (). getcontent ();

String value = Streamtool.decodestream (in);

2.2:post Way

HttpClient client = new Defaulthttpclient ();

//Http://188.188.4.100:8080/day06_android/login
HttpPost post = new HttpPost (path);

//Two key-value pairs
Namevaluepair pair1=new Basicnamevaluepair ("number", number);
Namevaluepair pair2=new basicnamevaluepair ("password", password);

//Put two key-value pairs in the list and then put the list into the entity
list<namevaluepair> List = new arraylist<namevaluepair> ();

List.add (PAIR1);
List.add (PAIR2);

//Here UTF-8 can encode the data and bring it over.
post.setentity (New urlencodedformentity (list, "UTF-8"));

HttpResponse response = Client.execute (post);

//Get the Status line object, and then get the status code in the status line
int code = response.getstatusline (). Getstatuscode ();

3 Use the Open source framework to send requests:

Go to GitHub to download the search for async http, downloaded to put the COM file into the project directory can be used, it is using the Asynchttpclient API

3.1:get Way:

Path = path+ "? number=" +number+ "&password=" +password;
Asynchttpclient client = new Asynchttpclient ();

Client.get (Path, new Asynchttpresponsehandler () {

//accesses the network, the server is called when it successfully processes the client's request
@Override
public void onsuccess (int statusCode, header[] headers,
byte[] responsebody) {

Toast.maketext (Mainactivity.this, "The result of the login is:" + new String (Responsebody), 0). Show ();

When a network is accessed, a request failure is invoked
@Override
public void onfailure (int statusCode, header[] headers,
Byte[] responsebody, throwable error) {

Toast.maketext (Mainactivity.this, "Sorry, the server is unresponsive ... ", 0). Show ();
}
});

3.2:post Way

asynchttpclient client = new Asynchttpclient ();

requestparams params = new Requestparams ();
params.add ("number", number);
params.add ("password", password);

client.post (Path, params,new Asynchttpresponsehandler () {

//accesses the network, the server is called when it successfully processes the client's request
@Override
public void onsuccess (int statusCode, header[] headers,
byte[] responsebody) {

Toast.maketext (Mainactivity.this, "The result of the post login is:" + new String (Responsebody), 0). Show ();

When a network is accessed, a request failure is invoked
@Override
public void onfailure (int statusCode, header[] headers,
Byte[] responsebody, throwable error) {

Toast.maketext (Mainactivity.this, "Sorry, the server is unresponsive ... ", 0). Show ();
}
});

Three sets of API implementations send a GET, POST request to the server

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.