Use of HttpURLConnection and httpclient

Source: Internet
Author: User

To do Android application development can not be separated from the network, it is necessary to use HTTP communication. There are two types of HTTP requests that we use frequently, such as post and get. Get can get a static page, you can put the parameters behind the URL string, passed to the server. The parameters of the Post method are placed in the HTTP request and passed to the server. A more detailed distinction can be found in the blog post: http://blog.csdn.net/yaojianyou/article/details/1720913/.

First look at httpurlconnection. HttpURLConnection is inherited from URLConnection, and objects are obtained primarily through the OpenConnection method of the URL, such as

url URL =  new  url ( " http://www.baidu.com " Span style= "word-wrap:normal; Word-break:normal "");  

/** get HttpURLConnection Object */

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

/** setting the input and output streams */

urlconn.setdooutput (true);

urlconn.setdoinput (true);

/** Set Request mode is post*/

Urlconn.setrequestmethod ("POST");

/**post request cannot use cache */

urlconn.setusecaches (false);

/** last to close the connection */

Urlconn.disconnection ();

However, HttpURLConnection uses the Get method by default, such as:
HttpURLConnection urlconn = (httpurlconnection) url.openconnection ();  
, * * Get read stream */
InputStreamReader in = new InputStreamReader (Urlconn.getinputstream ());  
/** Create bufferedreader*/
 bufferedreader buffer = new BufferedReader (in) for output,  
 string inputline = null ;  
/** Loop to read the obtained data */
while (((Inputline = Buffer.readline ()) = null))  
    { 
      Resultdata + = Inputline + "\ n";  
   }          
/** Close the stream and links */
 in.close ();  
Urlconn.disconnect ();

------------HttpClient----------------------------

Apache offers the HttpClient compared to the traditional JDK's own urlconnection, it adds ease of use and flexibility (specific differences, which we'll discuss later), and it's not only easy for the client to send HTTP requests, but also facilitates the developer to test the interface (based on the HTTP protocol). Which improves the efficiency of development and facilitates the robustness of the code.
An example of the action code for the Get method is as follows:

/** Request Address */
String Httpurl = "";
/** Get HttpGet Connection Object */
HttpGet HttpRequest = new HttpGet (Httpurl);
/** get httpclient*?
HttpClient HttpClient = new Defaulthttpclient ();
/** Get httpresponse*/
HttpResponse HttpResponse = Httpclient.execute (HttpRequest);
/** determine if the request is successfulGetstatuscode () ==200*/
if (Httpresponse.getstatusline (). Getstatuscode () = = HTTPSTATUS.SC_OK)
{
/** get returned to the string*
String strresult = entityutils.tostring (Httpresponse.getentity ());
} else{
Prompt for request error
}
}
If we use the post parameter, we use Namevaluepair to save the parameters, such as:
/** Request url*/
String Httpurl = "";
/** use post method to get HttpPost object */
HttpPost HttpRequest = new HttpPost (Httpurl);
/** must use Namevaluepair to save parameters */
list<namevaluepair> params = new arraylist<namevaluepair> ();
/** adding parameter values */
Params.add (New Basicnamevaluepair ("UserId", "555555"));

Params.add (New Basicnamevaluepair ("PassWord", "*******"));
/** Setting the character set */
Httpentity httpentity = new Urlencodedformentity (params, "UTF-8");
/** Request Operation */
Httprequest.setentity (httpentity);
/** Get httpclient*/
HttpClient HttpClient = new Defaulthttpclient ();
/** Get response*/
HttpResponse HttpResponse = Httpclient.execute (HttpRequest);
/** determine if the connection succeeded Getstatuscode () ==200 */
if (Httpresponse.getstatusline (). Getstatuscode () = = HTTPSTATUS.SC_OK)
{
/** return Results */
String strresult = entityutils.tostring (Httpresponse.getentity ());
}else{
Prompt error
}
}


Use of httpurlconnection and httpclient

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.