Java后端用HttpClient转发文件(文件访问中转)

Service代码:

public void relay(String url, HttpServletResponse resp){
		if(url==null || "".equals(url.trim())){
			return; // url为空时不处理
		}
	    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
	    CloseableHttpResponse response = null;
	    System.out.println("要转发的文件地址:"+url);
	    try {
	        response = httpClient.execute(new HttpGet(url));
	        HttpEntity entity = response.getEntity();
	        int status = response.getStatusLine().getStatusCode();
	        resp.setStatus(status);
	        if (status==200 && entity!=null) {
	            //Content-Type根据文件实际类型设置
	            resp.setHeader("Content-Type", "application/pdf;charset=utf-8");
	            resp.setHeader("Content-Length", entity.getContentLength()+"");
	            resp.setHeader("Content-Encoding", "UTF-8");
	
	            InputStream is = entity.getContent();
	            OutputStream os = resp.getOutputStream();
	
	            byte[] buffer = new byte[1024];
	            int ch;
	            while ((ch = is.read(buffer)) != -1) {
	                os.write(buffer, 0, ch);
	            }
	            is.close();
	            os.flush();
	            os.close();
	        }
	    } catch (IOException e) {
	        e.printStackTrace();
	    }finally {
	        try {
	            if (httpClient != null) {
	                httpClient.close();
	            }
	            if (response != null) {
	                response.close();
	            }
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	    }
	}
————————————————
版权声明:本文为CSDN博主「风喃海北」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/xhom_w/article/details/107243391

  Controller接口:

@GetMapping(value = "/relay")
    public void fileRelay(@RequestParam("url") String url, HttpServletResponse response){
        fileAccessService.relay(url, response);
    }
————————————————
版权声明:本文为CSDN博主「风喃海北」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/xhom_w/article/details/107243391

 这种方式会有个漏洞,就是没有把文件名称传回来,如果用浏览器直接下载的话,会出现问题的,现在只是获取了输入流和长度而已

 

posted @ 2022-07-19 10:43  信铁寒胜  阅读(1320)  评论(0编辑  收藏  举报