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());
//实际上URL的openConnection的返回值就是一个URLConnection
URLConnection c;
try {
c = url.openConnection();
c.setRequestProperty ("Authorization", "Basic " + encoding);
//用URLConnection的connect()方法建立连接
c.connect(); //*
// 显示该连接的相关信息,这些都是URLConnection的方法
System.out.println("内容类型: "+c.getContentType());
System.out.println("内容长度: "+c.getContentLength());
System.out.println("创建日期: "+new Date(c.getDate()));
System.out.println("最后修改日期: "+new Date(c.getLastModified()));
System.out.println("终止日期: "+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;
}
}
注意 关键:
String userPassword = theUsername + ":" + thePassword;
String encoding = new sun.misc.BASE64Encoder().encode (userPassword.getBytes());
c.setRequestProperty ("Authorization", "Basic " + encoding);