Java allows you to download images from the Internet and save them to a local device.
Package cn.net. ching;
Import java. io. ByteArrayOutputStream;
Import java. io. File;
Import java. io. FileOutputStream;
Import java. io. InputStream;
Import java.net. HttpURLConnection;
Import java.net. URL;
Public class ImageRequest {
/**
* @ Param args
*/
Public static void main (String [] args) throws Exception {
// A new URL object
URL url = new URL ("http://pic1.nipic.com/2008-12-15/20081215211851562_2.jpg ");
// Open the link
HttpURLConnection conn = (HttpURLConnection) url. openConnection ();
// Set the Request Method to "GET"
Conn. setRequestMethod ("GET ");
// Timeout response time is 5 seconds
Conn. setConnectTimeout (5*1000 );
// Obtain image data through the input stream
InputStream inStream = conn. getInputStream ();
// Obtain the binary data of the image. The data is encapsulated in binary format and universal.
Byte [] data = readInputStream (inStream );
// A new file object is used to save images. By default, the root directory of the current project is saved.
File imageFile = new File ("BeautyGirl16.jpg ");
// Create an output stream
FileOutputStream outStream = new FileOutputStream (imageFile );
// Write data
OutStream. write (data );
// Close the output stream
OutStream. close ();
}
Public static byte [] readInputStream (InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream ();
// Create a Buffer string
Byte [] buffer = new byte [1024];
// The length of the string to be read each time. If the value is-1, all the strings are read.
Int len = 0;
// Read data from the buffer using an input stream
While (len = inStream. read (buffer ))! =-1 ){
// Write data into the buffer using the output stream. The intermediate parameter indicates the position from which to start reading, and len indicates the read length.
OutStream. write (buffer, 0, len );
}
// Close the input stream
InStream. close ();
// Write data in outStream into memory
Return outStream. toByteArray ();
}
}