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 picture and save to the server hard drive
* @param imgurl
* @return Picture saved server path
*/
public static string GetImages (String imgurl) {
String Imgpath = "";
try{
New a URL object
URL url = new URL (imgurl);
Open link
HttpURLConnection conn = (httpurlconnection) url.openconnection ();
Set request mode to "GET"
Conn.setrequestmethod ("GET");
Timeout response time is 5 seconds
Conn.setconnecttimeout (5 * 1000);
Get picture data from an input stream
InputStream instream = Conn.getinputstream ();
Get the binary data of the picture, get the data in binary package, have universal
Byte[]data = Readinputstream (instream);
Imgpath = ImageRequest.class.getClassLoader (). GetResource (""). GetPath ();
Imgpath = Imgpath.split ("Web-inf") [0];
Imgpath = imgpath+ "images/" + "haha.jpg";
The new file object is used to save the image, and the current project root directory is saved by default
File ImageFile = new file (Imgpath);
Create an output stream
FileOutputStream OutStream = new FileOutputStream (imagefile);
Write Data
Outstream.write (data);
Turn off the output stream
Outstream.close ();
Server file path
Imgpath = Imgpath.split ("WebRoot") [1];
System.out.println (Imgpath);
}catch (Exception e) {e.printstacktrace ();}
return imgpath;
}
/**
* Read File stream
* @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 each read string, if 1, indicates that all reads are complete
int len = 0;
Use an input stream to read data from buffer
while ((Len=instream.read (buffer))! =-1) {
Writes data to buffer with the output stream, where the middle parameter represents the starting point to read, and Len represents the length of the read
Outstream.write (buffer, 0, Len);
}
Close the input stream
Instream.close ();
Write the data in the OutStream to memory
return Outstream.tobytearray ();
}
public static void Main (string[] args) throws Exception {
Imagerequest.getimages ("http://image.meilele.com/images/201311/1385338928366387259.jpg");
}
}
Save Java files to server