Android Experience 8--internet

Source: Internet
Author: User
Tags flush

1. Getting data from the Internet

Using the HttpURLConnection object, we can get the Web page data from the network.

Urlurl = new URL ("http://www.sohu.com");

Httpurlconnectionconn = (httpurlconnection) url.openconnection ();

Conn.setconnecttimeout (5*1000);/Set Connection timeout

Conn.setrequestmethod ("get");//Get method to initiate a request

if (Conn.getresponsecode ()!=) throw new RuntimeException ("Request URL failed");

Inputstreamis = Conn.getinputstream ()//get the input stream returned by the network

Stringresult = ReadData (IS, "GBK");

Conn.disconnect ();

The first parameter is the input stream, and the second parameter is the character set encoding

Publicstatic String ReadData (InputStream insream, string charsetname) throwsexception{

Bytearrayoutputstream OutStream = Newbytearrayoutputstream ();

byte[] buffer = new byte[1024];

int len =-1;

while (len = insream.read (buffer))!=-1) {

Outstream.write (buffer, 0, Len);

}

byte[] data = Outstream.tobytearray ();

Outstream.close ();

Insream.close ();

return new String (data, charsetname);

}

Using the HttpURLConnection object, we can get the file data from the network.

Urlurl = new URL ("http://photocdn.sohu.com/20100125/Img269812337.jpg");

Httpurlconnectionconn = (httpurlconnection) url.openconnection ();

Conn.setconnecttimeout (5*1000);

Conn.setrequestmethod ("get");

if (Conn.getresponsecode ()!=) throw new RuntimeException ("Request URL failed");

Inputstreamis = Conn.getinputstream ();

Readasfile (IS, "img269812337.jpg");

publicstatic void Readasfile (inputstream insream, File file) throws exception{

FileOutputStream OutStream = new FileOutputStream (file);

byte[] buffer = new byte[1024];

int len =-1;

while (len = insream.read (buffer))!=-1) {

Outstream.write (buffer, 0, Len);

}

Outstream.close ();

Insream.close ();

}

2. Multi-Threaded Download

The use of multi-threaded download files can be faster to complete the download of files, multithreaded download file is fast because of its preempted server resources. such as: Assuming that the server serves up to 100 users at the same time, one thread in the server corresponds to one user, 100 threads are not executed concurrently in the computer, but the CPU divides the time slice to perform alternately, if a application uses 99 threads to download the file, then it occupies 99 user resources. Suppose the average CPU execution time allocated to each thread in one second is that the 10ms,a application gets 990ms of execution time in one second of the server, while the other applies only 10ms execution time in a second. Just like a faucet, 990 milliseconds of water per second when the water is equal

It must be more than 10 milliseconds of water.

Multi-threaded Download implementation process:

1> first gets the length of the download file, and then sets the length of the local file.

Httpurlconnection.getcontentlength ();

Randomaccessfilefile = new Randomaccessfile ("QQWubiSetup.exe", "RW");

File.setlength (filesize)//Set the length of the local file

2> calculates the length and download location of each thread's downloaded data based on file length and number of threads. For example, the length of the file is 6M and the number of threads is 3, so each thread downloads a data length of 2M, where each thread starts downloading as shown above.

3> uses the HTTP Range header field to specify where each thread downloads from the file, such as: Specifies that the file be downloaded from the 2M location of the file, as follows:

Httpurlconnection.setrequestproperty ("Range", "bytes=2097152-");

4> saves the file and uses the Randomaccessfile class to specify where each thread starts writing data from the local file.

Randomaccessfilethreadfile = new Randomaccessfile ("QQWubiSetup.exe", "RW");

Threadfile.seek (2097152);//write data from where the file is located

3. send request parameters to the Internet

Using the HttpURLConnection object, we can send request parameters to the network.

Stringrequesturl = "Http://localhost:8080/itcast/contanctmanage.do";

map<string,string> requestparams = new hashmap<string, string> ();

Requestparams.put ("Age", "12");

Requestparams.put ("name", "China");

StringBuilder params = new StringBuilder ();

For (map.entry<string,string> Entry:requestParams.entrySet ()) {

Params.append (Entry.getkey ());

Params.append ("=");

Params.append (Urlencoder.encode (Entry.getvalue (), "UTF-8"));

Params.append ("&");

}

if (params.length () > 0) Params.deletecharat (params.length ()-1);

Byte[]data = Params.tostring (). GetBytes ();

Urlrealurl = new URL (Requesturl);

Httpurlconnectionconn = (httpurlconnection) realurl.openconnection ();

Conn.setdooutput (TRUE);//Send POST request must set allow output

Conn.setusecaches (false);//Do not use cache

Conn.setrequestmethod ("POST");

Conn.setrequestproperty ("Connection", "keep-alive");//Maintain long connection

Conn.setrequestproperty ("Charset", "UTF-8");

Conn.setrequestproperty ("Content-length", String.valueof (Data.length));

Conn.setrequestproperty ("Content-type", "application/x-www-form-urlencoded");

Dataoutputstreamoutstream = new DataOutputStream (Conn.getoutputstream ());

Outstream.write (data);

Outstream.flush ();

if (conn.getresponsecode () = = 200) {

String result =readasstring (Conn.getinputstream (), "UTF-8");

Outstream.close ();

SYSTEM.OUT.PRINTLN (result);

}

4. send XML data to the Internet

With the HttpURLConnection object, we can send XML data to the network.

Stringbuilderxml = new StringBuilder ();

Xml.append ("<?xmlversion=\" 1.0\ "encoding=\" utf-8\ "?>");

Xml.append ("<M1V=10000>");

Xml.append ("<ui=1 d=\" n73\ "> China </U>");

Xml.append ("</M1>");

Byte[]xmlbyte = Xml.tostring (). GetBytes ("UTF-8");

Urlurl = Newurl ("Http://localhost:8080/itcast/contanctmanage.do?method=readxml");

Httpurlconnectionconn = (httpurlconnection) url.openconnection ();

Conn.setconnecttimeout (5*1000);

Conn.setdooutput (TRUE);//Allow output

Conn.setusecaches (false);//Do not use cache

Conn.setrequestmethod ("POST");

Conn.setrequestproperty ("Connection", "keep-alive");//Maintain long connection

Conn.setrequestproperty ("Charset", "UTF-8");

Conn.setrequestproperty ("Content-length", String.valueof (Xmlbyte.length));

Conn.setrequestproperty ("Content-type", "Text/xml; Charset=utf-8");

Dataoutputstreamoutstream = new DataOutputStream (Conn.getoutputstream ());

Outstream.write (xmlbyte);//Send XML data

Outstream.flush ();

if (Conn.getresponsecode ()!=) throw new RuntimeException ("Request URL failed");

Inputstreamis = Conn.getinputstream ();//Get Return Data

Stringresult = Readasstring (IS, "UTF-8");

Outstream.close ();

5.<!--access to Internet permissions-->

<uses-permission

Android:name= "Android.permission.INTERNET"/>

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.