Httputils.java Network Download Tool class

Source: Internet
Author: User

Package Http;


import Java.io.ByteArrayOutputStream;
import java.io.IOException;
import Java.io.InputStream;
import java.net.HttpURLConnection;
import Java.net.URL;

/**
* Web download tool class
* Function: Download byte array, download text data
* Download Digital array (text picture mp3)
* Download Text data
* Created by lxj-pc on 2017/6/27.
*/
Public class Httputils {
Public Static byte[] get (String URL) throws IOException {
//Network Download
HttpURLConnection conn = (httpurlconnection) New URL
(URL). OpenConnection ();

InputStream is = Conn.getinputstream ();
Bytearrayoutputstream BAOs = null;

if (conn.getresponsecode () = =) {
BAOs = new Bytearrayoutputstream ();
byte[] buffer = new BYTE[8 * 1024];//8k
int len =-1;

//Gets the total length of the resource
int totallen = Conn.getcontentlength ();
int curlen = 0;
While (len = is.read (buffer))! =-1) {

baos.write (buffer, 0, Len);
//3. Calculating download Progress
Curlen + = len;
int p = curlen * 100/totallen;
System.out.println ("Jindu" + p + "%");

}

is.close ();
Conn.disconnect ();

}

return Baos.tobytearray ();
}

Public static string getText (string url) throws exception{


return new String (Get (URL), "Utf-8");

}

}

Httputils.java Network Download Tool class

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.