Android implements network programming via HttpURLConnection and HttpClient interfaces _android

Source: Internet
Author: User

The HttpURLConnection and HttpClient interfaces provided in Android can be used to develop HTTP programs. The following are some of the lessons learned.

1, HttpURLConnection interface

The first thing to be clear is the difference between post and get requests in HTTP traffic. Get can obtain a static page, or you can put parameters behind the URL string, passed to the server. The parameters of the Post method are placed in the HTTP request. Therefore, before programming, you should first explicitly use the request method, and then choose the appropriate programming method according to the way you use it. HttpURLConnection is inherited from the URLConnection class, both of which are abstract classes. Its object is obtained mainly through the OpenConnection method of the URL. The creation method is shown in the following code:

Copy Code code as follows:

URL url = new URL ("http://www.xxx.com/index.jsp?type=231");
HttpURLConnection urlconn= (httpurlconnection) url.openconnection ();

You can make some settings on the requested property by following these methods, as follows:

Copy Code code as follows:

Setting up input and output streams
Urlconn.setdooutput (TRUE);
Urlconn.setdoinput (TRUE);
Set the request mode to post
Urlconn.setrequestmethod ("POST");
Post requests cannot use slow
Urlconn.setusecaches (FALSE);
Urlconn.disconnection ();

HttpURLConnection uses the Get method by default, as shown in the following code:

Copy Code code as follows:

HttpURLConnection urlconn = (httpurlconnection) url.openconnection ();
InputStreamReader in = new InputStreamReader (Urlconn.getinputstream ());
BufferedReader buffer = new BufferedReader (in);
String inputline = null;
while (((Inputline = Buffer.readline ())!= null)) {
Resultdata + = Inputline + "\ n";
}
In.close ();
Urlconn.disconnect ();

If you need to use the Post method, you need to setrequestmethod the settings. The code is as follows:

Copy Code code as follows:

String Httpurl = "http://www.xxx.com/getUser.jsp";
String resultdata = "";
URL url = null;
try {
url = new URL (httpurl);
catch (Malformedurlexception e) {
LOG.E (Debug_tag, "malformedurlexception");
}
if (URL!= null) {
try {
HttpURLConnection urlconn = (httpurlconnection) url.openconnection ();
Because this is a POST request, the setting needs to be set to True
Urlconn.setdooutput (TRUE);
Urlconn.setdoinput (TRUE);
Urlconn.setrequestmethod ("POST"); Set the Post method
Urlconn.setusecaches (FALSE);
Urlconn.setinstancefollowredirects (TRUE);
Urlconn.setrequestproperty ("Content-type", "application/x-www-form-urlencoded");
These configurations must be completed before connect,
Note that the connection.getoutputstream will implicitly carry the connect.
Urlconn.connect ();

DataOutputStream Flow
DataOutputStream out = new DataOutputStream (Urlconn.getoutputstream ());
String content = "Name=" + Urlencoder.encode ("John", "GB2312");
Out.writebytes (content);
Out.flush ();
Out.close ();
catch (Exception e) {
//
}
}

2, HttpClient interface

HTTP operations can also be performed using the HttpClient interface provided by Apache. The actions for Get and post request methods are different. The action code example for the Get method is as follows:

Copy Code code as follows:

String Httpurl = "http://www.xxx.com/getUser.jsp?par=123";
HttpGet Connection Object
HttpGet HttpRequest = new HttpGet (Httpurl);
HttpClient httpclient = new Defaulthttpclient ();
HttpResponse HttpResponse = Httpclient.execute (HttpRequest);
Request succeeded
if (Httpresponse.getstatusline (). Getstatuscode () = = HTTPSTATUS.SC_OK) {
Gets the returned string
String strresult = entityutils.tostring (Httpresponse.getentity ());
Mtextview.settext (strresult);
} else {
Mtextview.settext ("Request error!");
}

When you use the Post method for parameter passing, you need to use Namevaluepair to hold the arguments that you want to pass. In addition, you need to set the character set that you are using. The code looks like this:

Copy Code code as follows:

String Httpurl = "http://www.xxx.com/getUser.jsp";
HttpPost HttpRequest = new HttpPost (Httpurl);
list<namevaluepair> params = new arraylist<namevaluepair> ();
Params.add (New Basicnamevaluepair ("UserId", "123"));
Httpentity httpentity = new Urlencodedformentity (params, "GB2312"); Setting the character set
Httprequest.setentity (httpentity);
Get the default httpclient
HttpClient httpclient = new Defaulthttpclient ();
Get HttpResponse
HttpResponse HttpResponse = Httpclient.execute (HttpRequest);
HTTPSTATUS.SC_OK indicates successful connection
if (Httpresponse.getstatusline (). Getstatuscode () = = HTTPSTATUS.SC_OK) {
Gets the returned string
String strresult = entityutils.tostring (Httpresponse.getentity ());
Mtextview.settext (strresult);
} else {
Mtextview.settext ("Request error!");
}

HttpClient is actually some encapsulation of Java-provided methods, the input-output stream operations in HttpURLConnection, which are uniformly encapsulated into httppost (HttpGet) and HttpResponse in this interface, so that Reduces the complexity of the operation.

The above mentioned is the entire content of this article, I hope you can enjoy.

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.