public RespBean downloadThirdFileHttpServletResponse response throws UnsupportedEncodingException String thirdUrl = httpsdppttianjinchinataxgovcn8443kpfwfpjfzzv1exportDzfpwjEwmWjgs=PDF&Jym=728E
要使此方法可用,您需要进行以下更改:
- 添加所需的导入语句:
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.UnsupportedEncodingException;
import java.util.Date;
- 将方法签名中的返回类型更改为
void,因为不需要将RespBean返回给调用者。
public void downloadThirdFile(HttpServletResponse response) throws UnsupportedEncodingException {
-
删除最后的
return语句,因为不再返回RespBean。 -
将
HttpServletResponse的response对象的getOutputStream()方法更改为response.getOutputStream(),以便在方法结束时自动关闭流。
最终的代码如下:
public void downloadThirdFile(HttpServletResponse response) throws UnsupportedEncodingException {
String thirdUrl = "https://dppt.tianjin.chinatax.gov.cn:8443/kpfw/fpjfzz/v1/exportDzfpwjEwmWjgs=PDF&Jym=728E&Fphm=23122000000008542853&Kprq=20230905145917&Czsj=1693897158216";
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment;filename=" + new String((DateUtil.format(new Date(), "yyyyMMddHHmmss") + ".pdf").getBytes(), "ISO-8859-1"));
if (StrUtil.isBlank(thirdUrl)) {
// 下载失败的处理逻辑
return;
}
if (!thirdUrl.toLowerCase().contains("http")) {
thirdUrl = "http://" + thirdUrl;
}
HttpURLConnection httpUrl = null;
BufferedInputStream in = null;
try {
URL url = new URL(thirdUrl);
httpUrl = (HttpURLConnection) url.openConnection();
httpUrl.connect();
if (httpUrl.getResponseCode() != 200) {
// 下载地址错误的处理逻辑
return;
}
in = new BufferedInputStream(httpUrl.getInputStream());
int len = 2048;
byte[] bytes = new byte[len];
while ((len = in.read(bytes)) != -1) {
response.getOutputStream().write(bytes, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
// 下载文件失败的处理逻辑
} finally {
if (httpUrl != null) {
httpUrl.disconnect();
}
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
response.getOutputStream().close();
response.getOutputStream().flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
``
原文地址: https://www.cveoy.top/t/topic/iYJ2 著作权归作者所有。请勿转载和采集!