/**
* 下载文件到某个路径
* @param url
* @param path
*/
public static long downloadFile(String url,String path){
StringBuffer sb = new StringBuffer();
PrintWriter out = null;
InputStream in = null;
FileOutputStream os = null;
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
// if(StringUtils.isNotBlank(serverCode)){
// long time = System.currentTimeMillis();
// StringBuilder bd = new StringBuilder().append(serverCode).append(time).append(secret);
// String md5 = "";
// try {
// md5 = SecretFactory.getInstance().getSecret(SecretType.MD5).encode(bd.toString());
// } catch (SecretException e1) {
// e1.printStackTrace();
// }
//
// String auth = serverCode + ";" + time + ";" + md5;
// conn.setRequestProperty("Authorization", auth);
// }
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(conn.getOutputStream());
out.print(sb.toString());
// flush输出流的缓冲
out.flush();
// 定义InputStream输入流来读取URL的响应
in = conn.getInputStream();
os = new FileOutputStream(path);
byte[] buffer = new byte[4*1024];
int read;
long size = 0;
while((read = in.read(buffer)) > 0){
os.write(buffer, 0, read);
size+=read;
}
return size;
}catch(Exception e){
e.printStackTrace();
return 0;
}finally{
out.close();
try {
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
os.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}