Android and the Internet (get resources, multithreaded breakpoint downloads, Get/post send, send XML)

Source: Internet
Author: User
Tags flush rar

getting data from the Internet

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

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

HttpURLConnection conn = (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");

InputStream is = Conn.getinputstream ();//Get the input stream returned by the network

String result = ReadData (IS, "GBK");

Conn.disconnect ();

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

public static string ReadData (InputStream insream, String charsetname) throws exception{

Bytearrayoutputstream OutStream = new Bytearrayoutputstream ();

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);

}
<!--access to INTERNET permissions--> <uses-permission android:name= "Android.permission.INTERNET"/>
Using the HttpURLConnection object, we can get the file data from the network. URL url = new URL ("Http://photocdn.sohu.com/20100125/Img269812337.jpg"); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setconnecttimeout (5* 1000); Conn.setrequestmethod ("get"); if (Conn.getresponsecode ()!=) throw new RuntimeException ("Request URL failed"); InputStream is = Conn.getinputstream ();  Readasfile (IS, "img269812337.jpg"); public static void Readasfile (InputStream insream, File file) throws exception{FileOutputStream OutStream = new FILEOUTPU Tstream (file); byte[] buffer = new byte[1024]; int len =-1;   while (len = insream.read (buffer))!=-1) {outstream.write (buffer, 0, Len);} Outstream.close (); Insream.close (); }
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, where the amount of water per second is equal, it must be more than 10 milliseconds to put 990 milliseconds of water. Multithreading Download Implementation process: 1> first get the length of the download file, and then set the length of the local file. Httpurlconnection.getcontentlength (); Randomaccessfile file = new Randomaccessfile ("QQWubiSetup.exe", "RW"); File.setlength (filesize)//Set the length of the local file 2> calculates the length of data and the download location for each thread based on the length of the file and the 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 starts downloading from a 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. Randomaccessfile threadfile = new Randomaccessfile ("QQWubiSetup.exe", "RW"); Threadfile.seek (2097152);//write data from where the file is located
Send request parameters to the Internet Using the HttpURLConnection object, we can send request parameters to the network. String Requesturl = "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 (); URL realurl = new URL (requesturl); HttpURLConnection conn = (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"); DataOutputStream OutStream = new DataOutputStream (Conn.getoutputstream ()); Outstream.write (data); Outstream.flush (); if (Conn.getresponsecode () = () {        string result = Readasstring (Conn.getinputstream (), "UTF-8");         outstream.close ();        &NBSP;SYSTEM.OUT.PRINTLN (result); } send XML data to the Internet Using the HttpURLConnection object, we can send request parameters to the network. String Requesturl = "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 (); URL realurl = new URL (requesturl); HttpURLConnection conn = (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"); DataOutputStream OutStream = new DataOutputStream (Conn.getoutputstream ()); Outstream.write (data); Outstream.flush (); if (Conn.getresponsecode () = () {        string result = Readasstring (Conn.getinputstream (), "UTF-8");         outstream.close ();        &NBSP;SYSTEM.OUT.PRINTLN (result); } send XML data to the Internet With the HttpURLConnection object, we can send XML data to the network. StringBuilder XML =  new StringBuilder (); Xml.append ("<?xml version=\" 1.0\ "encoding=\" utf-8\ "?>"); Xml.append ("<m1 v=10000>"); Xml.append ("<u i=1 d=\" n73\ "> China </U>"); Xml.append ("</M1>"); byte[] Xmlbyte = xml.tostring (). GetBytes ("UTF-8"); URL url = new URL ("Http://localhost:8080/itcast/contanctmanage.do?method=readxml"); HttpURLConnection conn = (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 "); DataOutputStream OutStream = new DataOutputStream (Conn.getoutputstream ()); Outstream.write (xmlbyte);//Send XML Data Outstream.flush ();if (Conn.getresponsecode ()!=) throw new RuntimeException ("Request URL failed"); InputStream is = Conn.getinputstream ()//Get return data String result = Readasstring (IS, "UTF-8"); Outstream.close ();


Size: 11.3 KB internet.rar (40.1 kb) Downloads: Multhreaddownload.rar (76.3 kb) Download times: Rescat.rar (77.2 kb) Download times: Web.ra R (2.4 MB) Download count: 139 View Picture Attachments

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.