转载网址:http://mzywqwq.blog.163.com/blog/static/958701220126355451960/
关于Java编码可以参考这篇文章: http://andyhu1007.iteye.com/blog/311583
<Connectorport="8080"protocol="HTTP/1.1"
connectionTimeout="20000"
URIEncoding="UTF-8"
redirectPort="8443"/>
/**
* 向指定URL下载文件
* @param url 发送请求的URL,包含要下载的文件名
* @param savePath 要保存的本地路径
*/
publicstaticvoid downloadFile(String url,String saveFile)
{
try
{
URL realUrl =new URL(encodeUrl(url,"utf-8"));
BufferedInputStreamin=newBufferedInputStream(realUrl.openStream());
File newFile =newFile(saveFile);
BufferedOutputStreamout=newBufferedOutputStream(newFileOutputStream(newFile));
byte[] buf =newbyte[2048];
int length =in.read(buf);
while(length !=-1)
{
out.write(buf,0, length);
length =in.read(buf);
}
in.close();
out.close();
}
catch(Exception e)
{
System.out.println("GET error!"+ e);
e.printStackTrace();
}
}
/**
* 将链接地址转换成网络路径,否则不支持中文
* @param str 要编码的链接
* @param encoding 编码格式
* @return 转换后的字符串
*/
publicstaticString encodeUrl(String str,String encoding)
{
try
{
StringBuilder sb =newStringBuilder();
int start =0;
for(int i =0; i < str.length(); i++)
{
if(str.charAt(i)=='/'|| str.charAt(i)==':')//URLEncoder会转换所有字符,此处跳过不需要转换的字符
{
sb.append(URLEncoder.encode(str.substring(start, i),encoding));
sb.append(str.charAt(i));
start = i +1;
}
}
if(start < str.length())
sb.append(URLEncoder.encode(str.substring(start), encoding));
return sb.toString().replace("+","%20");//空格被转换成"+",实际需要转换成"%20"
}
catch(UnsupportedEncodingException e)
{
e.printStackTrace();
}
returnnull;
}