URLDecoder 可以直接用java里面的工具包,如果不行,从源码里拷贝URLDecoder 和URLEncoder两个类 ,并引入。
@Autowired
private URLDecoder urlDecoder;
接口代码:
@GetMapping("/downloadPact/{url}")
@ApiOperation(value = "下载", notes = "下载", httpMethod = "GET")
public void downloadPact(@PathVariable(value = "url") String urlParam, HttpServletResponse response) throws IOException {
String url= urlDecoder.decode(urlParam,"UTF-8");
HttpURLConnection conn = null;
try {
File file = new File(url);
// 取得文件的后缀名。
String ext = file.getName().substring(file.getName().lastIndexOf(".") + 1).toLowerCase();
StringBuffer buffername = new StringBuffer(url.substring(url.lastIndexOf("/")+1));
String filename = buffername.toString();
URL path = new URL(url);
conn = (HttpURLConnection) path.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
InputStream fis = conn.getInputStream();// 通过输入流获取数据
byte[] buffer = readInputStream(fis);
if (null != buffer && buffer.length > 0) {
// 清空response
response.reset();
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename=" + new String((filename).getBytes("GBK"), "ISO8859_1"));
response.addHeader("Content-Length", "" + buffer.length);
OutputStream toClient = response.getOutputStream();
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
如果是Post请求,
@PostMapping("/downloadSubsPact")
@ApiOperation(value = "下载", notes = "下载", httpMethod = "Post")
public void downloadSubscribPact(@RequestParam(value = "url") String url, HttpServletResponse response) throws IOException {
输入流:
/**
* 从输入流中获取数据
* @return
* @throws Exception
*/
private byte[] readInputStream(InputStream fis) throws IOException {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while( (len=fis.read(buffer)) != -1 ){
outStream.write(buffer, 0, len);
}
fis.close();
return outStream.toByteArray();
}
全部评论