"Turn" Pro Android Learning Note (72): HTTP Service (6): HttpURLConnection

Source: Internet
Author: User
Tags http post

Directory (?) [-]

    1. How Http get is used
      1. Basic Small Example
      2. Use of cookies
      3. redirect
    2. A small example of HTTP post
      1. Basic Small Example

The article reproduced only for non-commercial nature, and can not be accompanied by virtual currency, points, registration and other conditions, reprint must indicate the source: http://blog.csdn.net/flowingflying/

Before we were all using httpclient for HTTP connection, in the last learning, HttpClient is far more complex than the encapsulation socket, there is a manager, there is a connection pool. Starting with the Android2.3 version, it is possible that the java.net.HttpURLConnection provides a smaller, lighter-load connection service. Detailed Details: http://developer.android.com/reference/java/net/HttpURLConnection.html

How to use Http Get basics Small Example

private void Httpurlconngettest () {
HttpURLConnection urlconn = null;
try{
URL url = new URL ("http://www.android.com/");

/* 【1 "Gets the HttpURLConnection object. by calling Url.openconnection () and adapting the type to a httpurlconnection type. If you are working with HTTPS, use Httpsurlconnecction, the relevant code reference: Http://developer.android.com/reference/javax/net/ssl/HttpsURLConnection.html */
urlconn = (httpurlconnection) url.openconnection ();

/*"2" handles the header of the request, setting the Timeout property. */
Urlconn.Setrequestproperty("Private-hello", "Hello world!"); /Add Property Test
Urlconn.setconnecttimeout (3000); Corresponds to Connection timeout
Urlconn.setreadtimeout (5000); Corresponding socket timeout

/*"3" handles the body of the request. HTTP Get no body, related in HTTP POST demo */

/*"4" read response。 */
"4.1" Get response code test
int responsecode =Urlconn.getresponsecode ();
LOG.D ("PRO", "Response code =" + Responsecode);
if (Responsecode = = HTTPURLCONNECTION.HTTP_OK) {
LOG.D ("PRO", "Test Get header information Content-type:" +Urlconn.getcontenttype ()); "4.2" Get header information test
Read body
BufferedReader in = new BufferedReader (
New InputStreamReader (
Urlconn.getinputstream ()));
String line = null;
while (line = In.readline ()) = null) {
LOG.D ("PRO", line);
}
In.close ();
}
}catch (Exception e) {
E.printstacktrace ();
}finally{
/ * "5" disconnect. */
if (urlconn! = null)
Urlconn.disconnect ();
}
}

HttpURLConnection looks really like the entire design is closer to the underlying TCP flow concept. From the scratch case, the custom header field has been successfully added: Private-hello:hello world!. We can construct an HTTP request message based on the desired properties. Httpurlconnectoion also supports 401 certification, but it is rarely used for this type of authentication, and SIP is still in use.

Use of cookies

A special cookie manager is included through Cookiehander and cookiemanager,httpurlconnection to maintain a long session in client and server parts. This part of the code comes from reference.
Cookiemanager Cookiemanager = new Cookiemanager ();
Cookiehandler.setdefault (Cookiemanager);
Small examples of writing and reading cookies
HttpCookie cookie = new HttpCookie ("Lang", "fr");
Cookie.setdomain ("twitter.com");
Cookie.setpath ("/");
Cookie.setversion (0);
Cookiemanager.getcookiestore (). Add (New URI ("http://twitter.com/"), cookie);

redirect

HttpURLConnection can automatically handle the redirection situation and modify the code to perform the relevant tests. The httpurlconnection can support up to 5 redirects (presumably to prevent loops), but cannot cross scheme, which means that HTTP redirection to HTTPS is not possible, and vice versa, because HTTP and HTTPS are handled by different classes. Of course the browser is a redirect that supports cross-scheme. The httpurlconnection automatically connects to the location information given by the 302 found message.

URL url = new URL ("http://www.google.com/"); will be redirected to WWW.GOOGLE.COM.HK
... ...
/* 4, read response */
if (! Url.gethost (). Equals (Urlconn.geturl (). GetHost ()))//Compare the requested URL and the actual URL
LOG.D ("PRO", "Redirect to" + Urlconn.geturl (). GetHost ());
... ...

Small example of a small example of HTTP post

If Setdooutput (true) is set, this indicates an HTTP POST. If other, such as Options,head,put,delete and Trace, can be set by Setrequestmethod (String), nothing more than to determine how the status line is written.

private void Httpurlconnposttest () {
HttpURLConnection urlconn = null;
try{
URL url = new URL ("Http://blog.csdn.net/flowingflying1");//This is an invalid address, expected to reply 403
Urlconn = (httpurlconnection) url.openconnection ();

/ * "3" Processing request body */
Urlconn.setdooutput (true);
Set allow output, which can be provided with the request body
For better performance, you should set setfixedlengthstreamingmod (int) or setchunkedstramingmode (int). If not set, the request will be with the buffer has completed the body of the write, and then send, which is a large amount of body data is obviously less efficient.
urlconn.setchunkedstreamingmode (0);
By OutStream, write to Body
OutputStream out = new Bufferedoutputstream (Urlconn.getoutputstream ());
String content = "User=myfriend&action=test";
Out.write (Content.getbytes ());
Out.close ();

/* 4, read response. */
if (urlconn.getresponsecode () = HTTPURLCONNECTION.HTTP_OK) {
BufferedReader in = new BufferedReader (
New InputStreamReader (
Urlconn.getinputstream ()));
String line = null;
while (line = In.readline ()) = null) {
LOG.D ("PRO", line);
}
In.close ();
}
}catch (Exception e) {
E.printstacktrace ();
}finally{
if (urlconn! = null)
Urlconn.disconnect ();
}
}

The example code covered in this blog post can be downloaded in the Pro Android Learning: Http Service Small example.

RELATED Links: My Android development related articles

"Turn" Pro Android Learning Note (72): HTTP Service (6): HttpURLConnection

Related Article

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.