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