HTTP Communication httpurlconnection interface developed for Android

Source: Internet
Author: User
HTTP Communication httpurlconnection interface developed for Android

/*

* HTTP Communication httpconnection interface developed for Android

* Beijing Android Club group: 167839253

* Created on: 2012-5-9

* Author: blueeagle

* Email: liujiaxiang@gmail.com

*/

This article summarizes the httpurlconnection interface of HTTP Communication in the secrets of Android application development.

Httpurlconnection Interface

In the HTTP Communication Protocol, get and post are the most used. GET requests can obtain static pages, or put parameters after strings and pass them to the server. The difference between post and get is that the post parameter is not placed in the URL string, but in the HTTP request data.

Httpurlconnection is a standard Java class that inherits from the urlconnection class;

The httpurlconnection and urlconnection classes are both abstract classes and cannot be directly instantiated.

The object is mainly obtained through the openconnection method of the URL.

 

Instance definition code:

// Construct a URL object url = new URL (httpurl); // use httpurlconnection to open the link. urlconn is the Instance Object httpurlconnection urlconn = (httpurlconnection) URL. openconnection ();

The openconnection method only creates an httpurlconnection or urlconnection instance and does not perform real link operations.

Each openconnection operation creates a new instance.

Therefore, you can set the attributes of this object before connection.

// Set the urlconn of the input (output) stream. setdooutput (true); urlconn. setdoinput (true); // set urlconn in post mode. setrequestmethod ("Post"); // The cached urlconn cannot be used for post requests. setusecaches (false); // you can disable urlconn after the connection is complete. disconnect ();

 

Get a webpage content using get and post methods.

Httpurlconnection uses the get method by default. If you want to use the post method, you need to set the setrequestmethod. Then, write the parameter content to be passed to the data stream through the weitebytes method.

Code without parameters accessed by get:

/** Httpurlconnectionactivity02.java * Beijing Android Club group: 167839253 * created on: 2012-5-9 * Author: blueeagle * Email: liujiaxiang@gmail.com */public class httpurlconnectionactivity02 extends activity {/** called when the activity is first created. */private final string debug_tag = "httpurlconnectionactivityactivity"; @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinst Ancestate); setcontentview (R. layout. main); textview mtextview = (textview) This. findviewbyid (R. id. mytextview); // HTTP address string httpurl = "http: // 10.1.69.34/http1.jsp"; // the obtained data string resultdata = ""; Url url = NULL; try {// construct a URL object url = new URL (httpurl);} catch (malformedurlexception e) {log. E (debug_tag, "malformedurlexception");} If (URL! = NULL) {try {// use httpurlconnection to open the connection httpurlconnection urlconn = (httpurlconnection) URL. openconnection (); // The read content (Stream) inputstreamreader in = new inputstreamreader (urlconn. getinputstream (); // create bufferedreaderbufferedreader buffer = new bufferedreader (in) for the output; string inputline = NULL; // use a loop to read the obtained data while (inputline = buffer. readline ())! = NULL) {// Add "\ n" next to each row to wrap resultdata + = inputline + "\ n";} If (! Resultdata. equals ("") {mtextview. settext (resultdata);} else {mtextview. settext ("the read content is null");} // disable inputstreamreaderin. close (); // close the HTTP connection urlconn. disconnect (); // set to display the obtained content} catch (ioexception e) {log. E (debug_tag, "ioexception") ;}} else {log. E (debug_tag, "url null");} // set the button event listening button button_back = (button) findviewbyid (R. id. button_back);/* listen to button event information */button_back.setonclicklistener (New button. onclicklistener () {public void onclick (view v) {/* Create an intent object */intent = new intent ();/* specify the intent class */intent. setclass (httpurlconnectionactivity02.this, httpurlconnectionactivity. class);/* start a new activity */startactivity (intent);/* close the current activity */httpurlconnectionactivity02.this. finish ();}});}}

Post access to the server, and access to the server images and display them on the client.

The Code is as follows:

/** Httpurlconnectionactivity02.java * Beijing Android Club group: 167839253 * created on: 2012-5-9 * Author: blueeagle * Email: liujiaxiang@gmail.com */public class httpurlconnectionactivity03 extends activity {/** called when the activity is first created. */private final string debug_tag = "activity03"; private bitmap BMP; @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstance State); setcontentview (R. layout. main); textview mtextview = (textview) This. findviewbyid (R. id. mytextview); imageview mimageview = (imageviewdomainthis.findviewbyid(r.id.bmp); // HTTP address string httpurl = "http: // 10.1.69.34/http1.jsp"; // the obtained data string resultdata = ""; URL url = NULL; try {// construct a URL object url = new URL (httpurl);} catch (malformedurlexception e) {log. E (debug_tag, "malformedurlexception");} If (URL! = NULL) {try {// use httpurlconnection to open the link httpurlconnection urlconn = (httpurlconnection) URL. openconnection (); // *********************************** different places of post Method * ************************************//// because this is a POST request, it must be set to trueurlconn. setdooutput (true); urlconn. setdoinput (true); // set urlconn in post mode. setrequestmethod ("Post"); // The cached urlconn cannot be used for post requests. setusecaches (false); urlconn. setinstancefollowredirects (true); // configure the C for this connection Ontent_type, configured as application/x-www-form-urlencodedurlConn.setRequestProperty ("Content-Type", "application/X-WWW-form-urlencoded"); // connection, from posturl. the current configuration of openconnection () must be completed before connect. // Note the connection. getoutputstream implicitly performs connect. // *********************************** different places of post Method * *********************************** // urlconn. connect (); // dataoutputstream stream. Dataoutputstream out = new dataoutputstream (urlconn. getoutputstream (); // string content = "par =" + urlencoder. encode ("abcdef", "gb2312"); // write the content to be uploaded to the stream out. writebytes (content); // refresh and close out. flush (); out. close (); // get data bufferedreader reader = new bufferedreader (New inputstreamreader (urlconn. getinputstream (); string inputline = NULL; // --- // The read content (Stream) // --- inputstreamreader in = new inputstreamreader (u Rlconn. getinputstream (); // --- // create bufferedreader for the output // --- bufferedreader buffer = new bufferedreader (in); // --- string inputline = NULL; // --- // use a loop to read the obtained data while (inputline = reader. readline ())! = NULL) {// Add "\ n" next to each row to wrap resultdata + = inputline + "\ n";} reader. close (); // close the HTTP link urlconn. disconnect (); // set to display the obtained content if (! Resultdata. equals ("") {mtextview. settext (resultdata); BMP = This. getnetbitmap ("http: // 10.1.69.34/0.jpg"); mimageview. setimagebitmap (BMP);} else {mtextview. settext ("the read content is blank");} // close inputstreamreaderreader. close (); // close the HTTP connection urlconn. disconnect (); // set to display the obtained content} catch (ioexception e) {log. E (debug_tag, "ioexception") ;}} else {log. E (debug_tag, "url null");} // set the button event listening button button_back = (button) findviewbyid (R. id. button_back);/* listen to button event information */button_back.setonclicklistener (New button. onclicklistener () {public void onclick (view v) {/* Create an intent object */intent = new intent ();/* specify the intent class */intent. setclass (httpurlconnectionactivity03.this, httpurlconnectionactivity. class);/* start a new activity */startactivity (intent);/* close the current activity */httpurlconnectionactivity03.this. finish ();}});} // ********************************** to obtain network images (BMP supported), JPG, PNG, GIF, and other formats, but the BMP format is relatively small) * **********************************/Public bitmap getnetbitmap (string URL) {URL imageurl = NULL; Bitmap bitmap = NULL; try {imageurl = new URL (URL);} catch (malformedurlexception e) {log. E (debug_tag, E. getmessage ();} Try {httpurlconnection conn = (httpurlconnection) imageurl. openconnection (); Conn. setdoinput (true); Conn. connect (); // convert the obtained data to inputstream is = Conn. getinputstream (); // converts inputstream to Bitmap bitmap = bitmapfactory. decodestream (is); is. close ();} catch (ioexception e) {log. E (debug_tag, E. getmessage () ;}return bitmap ;}}

 

Summary:

For http:

The get method is passed by attaching the parameter key-value pair to the URL, which is a text method.

The server can directly read data from the 'query _ string' variable, which is highly efficient. However, it lacks security and cannot process complicated data with limited length. It is mainly used to pass simple parameters.

Post mode: In transmission mode, parameters are packaged and transmitted in the HTTP header, which can be binary.
Read from the content_length environment variable to facilitate the transmission of larger data. At the same time, because the data is not exposed in the address bar of the browser, the security is relatively high, however, such processing efficiency will be affected.

 

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.