关于下载音乐的问题
Published in:2022-04-30 | category: 项目

        这周写项目遇到了一个问题——怎么通过url下载音乐文件。

        因为之前写下载文件都是通过文件路径去下载的,而这一次我们用到了云存储,在数据库里面存的是url地址,所以我就不知道应该怎么去下载了。后来我在网上找到了通过url来下载文件的方法,但是又遇到了一个问题,就是我是从数据库获取的url,里面有中文会报错,这个问题困扰了我好长时间。

        我在网上查找解决中文乱码的办法的时候,知道了URLEncoder.encode()可以使用指定的编码机制将字符串转换为 application/x-www-form-urlencoded 格式 ,从而解决中文乱码。但是我在使用了URLEncoder.encode()之后,发现接口报错HTTP response code: 400 for URL,显示发送了异常请求,后来才发现并不能将url全部进行转化,否者会把HTTP:// 中的斜线也转义,导致请求出现协议异常等问题。

        后来由于我找不到更好的办法对url中的中文进行处理,就将url分割成了几部分,然后对含有中文的那一部分进行转化。虽然方法有点笨,但是总算是解决了问题。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
public ModelAndView download(Integer musicId,  HttpServletResponse response) throws Exception {
Map map=new HashMap();
Music music =musicService.queryById(musicId);
String musicName=music.getMusicName();
String musicPath=music.getMusicPath();
ServletOutputStream out = null;
InputStream inputStream = null;
String[] str=musicPath.split("/",4);
String[] s=str[3].split("\\.");
try {
//路径
String path = musicPath;
System.out.println(path);
// 取得文件的后缀名。
String ext = path.substring(path.lastIndexOf(".") + 1).toLowerCase();
//文件名
String pdfName = musicName+"."+ext;
// 获取外部文件流
URL url = new URL(str[0]+"//"+str[2]+"/"+URLEncoder.encode(s[0], "UTF-8")+"."+s[1]);
map.put("2",url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(3 * 1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
inputStream = conn.getInputStream();
/**
* 输出文件到浏览器
*/
int len = 0;
// 输出 下载的响应头,如果下载的文件是中文名,文件名需要经过url编码
response.setContentType("application/x-download");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(pdfName, "UTF-8"));
response.setHeader("Cache-Control", "no-cache");
out = response.getOutputStream();
byte[] buffer = new byte[1024];
while ((len = inputStream.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception e) {
}
}
if (out != null) {
try {
out.close();
} catch (Exception e) {
}
}
}
return new ModelAndView();
}
Prev:
项目考核总结
Next:
音乐项目总结(三)