Android Get Network pictures

Source: Internet
Author: User

ImportJava.io.ByteArrayOutputStream;ImportJava.io.File;ImportJava.io.FileOutputStream;ImportJava.io.InputStream;Importjava.net.HttpURLConnection;ImportJava.net.URL;Importorg.junit.Test; Public classinternettest{@Test Public voidGetImage ()throwsException {//fail ("not yet implemented"); //first we want to get the requested path, the path is the resource we want to getString URLPath = "Http://pica.nipic.com/2008-05-23/200852381811521_2.jpg"; //Create a URL object, throw an exceptionURL url =NewURL (URLPath); //Get HttpURLConnection ObjectHttpURLConnection conn =(HttpURLConnection) url.openconnection (); //Claim Request MethodConn.setrequestmethod ("GET"); //Setting the connection timeoutConn.setconnecttimeout (6 * 1000); //Connection Successful        if(Conn.getresponsecode () = = 200)        {            //get the data back from the server, the input stream is relative to usInputStream InputStream =Conn.getinputstream (); //Get the data            byte[] data =Readinstream (InputStream); //Create a Save fileFile File =NewFile ("Xiaocai.jpg"); //Create a file output streamFileOutputStream OutputStream =Newfileoutputstream (file); //Write all of our binary data into the files we've built.outputstream.write (data); //turn off the output streamOutputstream.close (); }    }    //read the contents of a stream file     Public byte[] Readinstream (InputStream inputstream)throwsException {bytearrayoutputstream Bytearrayoutputstream=NewBytearrayoutputstream (); //declaring buffers        byte[] buffer =New byte[1024]; //Define read default length        intLength =-1;  while(length = inputstream.read (buffer))! =-1)        {            //output the buffer into memoryBytearrayoutputstream.write (buffer, 0, length); }        //turn off the output streamBytearrayoutputstream.close (); //close the input streamInputstream.close (); //returns a byte array of this output stream        returnBytearrayoutputstream.tobytearray (); }}

Android Get Network pictures

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.