Springboo通过http请求获取文件流下载到浏览器
Springboo通过http请求获取文件流下载到浏览器
httpurlconnection下载pdf文件打不开的原因,和解决代码
输入流转成输出流到浏览器客户端(PDF下载)
@ApiOperation(value="电子保单下载",notes="电子保单下载") @RequestMapping(value="/getDownloadOrder",method=RequestMethod.GET) public void getDownloadOrder(HttpServletRequest request, HttpServletResponse response) { String address = request.getParameter("url"); System.out.println("url:"+address); /* // try { *//*if(StringUtils.isNotBlank(url)){ String[] splitUrl = url.split("\\?"); url = splitUrl[0]+"?"+URLEncoder.encode( splitUrl[1]); }*//* url += "&hh=hh"; System.out.println("url:"+url); response.sendRedirect(url); } catch (IOException e) { e.printStackTrace(); }*/ InputStream fis = null; BufferedInputStream bis = null; OutputStream toClient = null; byte[] buffer = new byte[1024]; try { URL url = new URL(address); URLConnection urlConnection = url.openConnection(); HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection; // true -- will setting parameters httpURLConnection.setDoOutput(true); // true--will allow read in from httpURLConnection.setDoInput(true); // will not use caches httpURLConnection.setUseCaches(false); // setting serialized httpURLConnection.setRequestProperty("Content-type", "application/x-java-serialized-object"); // default is GET httpURLConnection.setRequestMethod("GET"); httpURLConnection.setRequestProperty("connection", "Keep-Alive"); httpURLConnection.setRequestProperty("Charsert", "UTF-8"); // 1 min httpURLConnection.setConnectTimeout(60000); // 1 min httpURLConnection.setReadTimeout(60000); // connect to server (tcp) httpURLConnection.connect(); int resultCode = httpURLConnection.getResponseCode(); if (resultCode == 200) { //获取文件名称 Map<String, List<String>> map = httpURLConnection.getHeaderFields(); for (String key : map.keySet()) { List<String> list = map.get(key); for (String str : list) { System.out.println(key + ":" + new String(str.getBytes("ISO-8859-1"), "GBK")); } } String contentDisposition = null; try { contentDisposition = new String(httpURLConnection.getHeaderField("Content-Disposition").getBytes("ISO-8859-1"), "GBK"); } catch (Exception e){ toClient = new BufferedOutputStream(response.getOutputStream()); toClient.write("<p style=\"font-size:50px;\">电子保单不存在或者正在生成中,请稍后重试!<a href=\"javascript:history.back(-1)\">返回</a></p>".getBytes("GBK")); return; } String[] split = contentDisposition.split("="); String fileName = split[1]; System.out.println("文件名称"+split[1]); response.reset(); //response.setCharacterEncoding("gbk"); response.setContentType("text/html; charset=UTF-8"); response.setHeader("content-Type", "application/pdf"); // 设置一个响应头,无论是否被浏览器解析,都下载 response.setHeader("Content-disposition", "attachment; filename=" + fileName); fis = httpURLConnection.getInputStream(); toClient = new BufferedOutputStream(response.getOutputStream()); bis = new BufferedInputStream(fis); int i = bis.read(buffer); while (i != -1) { toClient.write(buffer, 0, i); i = bis.read(buffer); } } else { toClient = new BufferedOutputStream(response.getOutputStream()); toClient.write("保单下载服务器异常,请稍后重试!".getBytes(StandardCharsets.UTF_8)); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (fis != null) { fis.close(); } } catch (IOException ex) { ex.printStackTrace(); } try { if (bis != null) { bis.close(); } } catch (IOException ex) { ex.printStackTrace(); } try { if (toClient != null) { toClient.close(); } } catch (IOException ex) { ex.printStackTrace(); } } }
2.linux 系统 写入txt 文件 更换port
package com.example.demo.service; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * @program: microadmin-server * @description * @author: zhaoJs * @create: 2022-02-07 14:03 **/ @Component @Slf4j public class FireWallService { public String updatePort(String port) { if (!port.matches("^[0-9]*[1-9][0-9]*$")||StringUtils.isBlank(port)||port.length()>4) { return "请输入四位数内的端口号"; } List<String> stringList = new ArrayList<>(); executeLinuxCmd("systemctl stop sds-libev"); //端口号 //String port = String.valueOf(Math.round((Math.random()+1) * 1000)); String template = "{\n" + " \"server\":\"104.243.27.97\",\n" + " \"server_port\":%s,\n" + " \"local_port\":1080,\n" + " \"password\":\"p@ssw0rd\",\n" + " \"timeout\":60,\n" + " \"method\":\"chacha20-ietf-poly1305\"\n" + "}"; template = String.format(template,port); stringList.add(template); writeDataHubData(stringList,"config"); executeLinuxCmd("systemctl start sds-libev"); return port; } /** * 写入txt文件 * * @param result * @param fileName * @return */ public static boolean writeDataHubData(List<String> result, String fileName) { long start = System.currentTimeMillis(); List<String> filePaths = new ArrayList(); String os = System.getProperty("os.name"); if(os.toLowerCase().startsWith("win")){ filePaths.add("D:\\temp\\txt"); filePaths.add("D:\\temp1\\txt"); }else { filePaths.add("/etc/sds"); filePaths.add("/etc/sds-libev"); } boolean flag = false; try { if (result != null && !result.isEmpty() && StringUtils.isNotEmpty(fileName)) { // fileName += "_" + System.currentTimeMillis() + ".txt"; fileName += ".json"; for (String filePath : filePaths){ File pathFile = new File(filePath); if (!pathFile.exists()) { pathFile.mkdirs(); } String relFilePath = filePath + File.separator + fileName; File file = new File(relFilePath); if (!file.exists()) { file.createNewFile(); } BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "GBK")); for (String info : result) { out.write(info); out.newLine(); } out.close(); } flag = true; } } catch (IOException e) { e.printStackTrace(); } finally { return flag; } } /* * * @Description: 执行linux 命令 * @Param: [cmd] * @Author: ZhaoJs * @Date: 2022/2/14 * @Version: 1.0 **/ public void executeLinuxCmd(String cmd) { log.info("got cmd job : " + cmd); Runtime run = Runtime.getRuntime(); try { Process process = run.exec(cmd); InputStream in = process.getInputStream(); BufferedReader bs = new BufferedReader(new InputStreamReader(in)); StringBuffer out = new StringBuffer(); byte[] b = new byte[8192]; for (int n; (n = in.read(b)) != -1;) { out.append(new String(b, 0, n)); } in.close(); process.destroy(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { /* List<String> stringList = new ArrayList<>(); //端口号 String port = String.valueOf(Math.round((Math.random()+1) * 1000)); String template = "{\n" + " \"server\":\"104.243.27.97\",\n" + " \"server_port\":%s,\n" + " \"local_port\":1080,\n" + " \"password\":\"p@ssw0rd\",\n" + " \"timeout\":60,\n" + " \"method\":\"chacha20-ietf-poly1305\"\n" + "}"; template = String.format(template,port); stringList.add(template); writeDataHubData(stringList,"config");*/ String repx = "^[0-9]*[1-9][0-9]*$"; System.out.println("112".matches("^[0-9]*[1-9][0-9]*$")); } }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升