Save the java file to the server, and save the java file to the server.
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 {
/**
* Read the network image and save it to the server hard disk.
* @ Param imgUrl
* @ Return the path of the server where the image is saved
*/
Public static String getImages (String imgUrl ){
String imgPath = "";
Try {
// A new URL object
URL url = new URL (imgUrl );
// 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 );
ImgPath = ImageRequest. class. getClassLoader (). getResource (""). getPath ();
ImgPath = imgPath. split ("WEB-INF") [0];
ImgPath = imgPath + "images/" + "haha.jpg ";
// A new file object is used to save images. By default, the root directory of the current project is saved.
File imageFile = new File (imgPath );
// Create an output stream
FileOutputStream outStream = new FileOutputStream (imageFile );
// Write data
OutStream. write (data );
// Close the output stream
OutStream. close ();
// Server File Path
ImgPath = imgPath. split ("WebRoot") [1];
System. out. println (imgPath );
} Catch (Exception e) {e. printStackTrace ();}
Return imgPath;
}
/**
* Reading file streams
* @ Param inStream
* @ Return
* @ Throws Exception
*/
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 ();
}
Public static void main (String [] args) throws Exception {
ImageRequest. getImages ("http://image.meilele.com/images/201311/1385338928366387259.jpg ");
}
}