Package com. test;
Import java. io. BufferedOutputStream;
Import java. io. File;
Import java. io. FileOutputStream;
Import java. io. IOException;
Import java. io. InputStream;
Import java. io. OutputStream;
Import java.net. MalformedURLException;
Import java.net. URL;
Import java.net. URLConnection;
Import java. util. Date;
Public class Test {
/**
* @ Param args
*/
Public static void main (String [] args ){
String imageurl = "http://www.baidu.com/img/logo-yy.gif ";
URL url;
String theUsername = "test ";
String thePassword = "test ";
Try {
Url = new URL (imageurl );
String userPassword = theUsername + ":" + thePassword;
String encoding = new sun. misc. BASE64Encoder (). encode (userPassword. getBytes ());
// The actual URL's openConnection return value is a URLConnection
URLConnection c;
Try {
C = url. openConnection ();
C. setRequestProperty ("Authorization", "Basic" + encoding );
// Use the connect () method of URLConnection to establish a connection
C. connect ();//*
// Display information about the connection. These are the URLConnection methods.
System. out. println ("content type:" + c. getContentType ());
System. out. println ("Content Length:" + c. getContentLength ());
System. out. println ("creation Date:" + new Date (c. getDate ()));
System. out. println ("Last modified Date:" + new Date (c. getLastModified ()));
System. out. println ("End Date:" + new Date (c. getExpiration ()));
InputStream in = c. getInputStream ();
String pathName = saveTempFile (in, "test.jpg ");
System. out. println (pathName );
} Catch (IOException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}//*
} Catch (MalformedURLException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
}
Private static String saveTempFile (InputStream inputStream, String fllename ){
String pathName = getTempFileName (fllename );
File tmpFile = new File (pathName );
OutputStream out = null;
Try {
Out = new BufferedOutputStream (new FileOutputStream (tmpFile ));
Int length = 1024*1024;
Byte [] buffer = new byte [length];
While (length = inputStream. read (buffer)> 0 ){
Out. write (buffer, 0, length );
}
} Catch (Exception e ){
E. printStackTrace ();
// Global. logger. error ("save temp file exception! ");
} Finally {
ResourceMgr. closeQuietly (out );
}
Return pathName;
}
Private static String getTempFileName (String filename ){
// Return System. getProperty ("user. dir") + File. separator + System. currentTimeMillis () + ". gif ";
Return System. getProperty ("user. dir") + File. separator + filename;
}
}
Note:
String userPassword = theUsername + ":" + thePassword;
String encoding = new sun. misc. BASE64Encoder (). encode (userPassword. getBytes ());
C. setRequestProperty ("Authorization", "Basic" + encoding );