欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

通过HttpURLConnection调用文件服务,实现文件下载

程序员文章站 2024-02-04 20:32:16
...

通过HttpURLConnection调用文件服务,实现文件下载

前端请求A服务controller,A服务通过HttpURLConnection方式请求到B服务,B服务再将文件返回给A服务,A服务用文件流的方式写入下载
一、A服务通过HttpURLConnection调用B服务接口获取File文件
参数介绍:
(1)urlStr:调用服务地址:http://xxx:8080/xxx/xxx?fileId = xxxx
(2)downloadDir:文件下载路径

public static File fileDownload(String urlStr, String downloadDir){
    File file = null;
     try {
         // 统一资源
         URL url = new URL(urlStr);
         // 连接类的父类,抽象类
         URLConnection urlConnection = url.openConnection();
         // http的连接类
         HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
         // 设定请求的方法,默认是GET
         httpURLConnection.setRequestMethod("GET");
         // 设置字符编码
         httpURLConnection.setRequestProperty("Charset", CHARSET);
         // 打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)。
         httpURLConnection.connect();
         // 文件大小
         int fileLength = httpURLConnection.getContentLength();
         System.out.println("file length---->" + fileLength);
         URLConnection con = url.openConnection();
         BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());
         file = new File(downloadDir);
         if (!file.exists()) {
             OutputStream out = new FileOutputStream(file);
             int size = 0;
             int len = 0;
             byte[] buf = new byte[1024];
             while ((size = bin.read(buf)) != -1) {
                 len += size;
                 out.write(buf, 0, size);
             }
             out.flush();
             out.close();
         }
         bin.close();
     } catch (MalformedURLException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
     } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
     } finally {
         return file;
     }
}

二、B服务端controller

@RequestMapping(value = "downloadFile",method = {RequestMethod.GET})
public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws Exception{
	response.setCharacterEncoding("utf-8");
	String fileId = request.getParameter("fileId");
	//通过查询数据库获取到保存的文件路劲,或者之前用接口传来文件路径查找也行
	File file = new File(filePath);
	//获取
	InputStream inputStream = new FileInputStream(file)
	String fileName = new String(file.getFileName().getBytes(), "UTF-8");
	//设置返回头
	response.setContentType("multipart/form-data");
	response.setHeader("Content-Disposition","attachment;filename=" + fileName);
	OutputStream os = response.getOutputStream();
		byte[] b = new byte[2048];
		int length;
		while ((length = inputStream.read(b)) > 0) {
			os.write(b, 0, length);
			os.flush();
		}
	os.close();
	inputStream.close();
}

三、A服务controller
参数:fileId:文件Id

@RequestMapping(value = "downloadFile",method = {RequestMethod.POST})
public String downloadFile(@RequestBody String fileId , HttpServletRequest request , HttpServletResponse response) throws Exception{
	//调用fileDownload方法,详见第一步:客户端通过HttpURLConnection获取B服务中的文件
	String urlStr = "http://xxx:8080/xxx/xxx?fileId = xxxx";
	String downloadDir = "E/xxxx/";
	File file = fileDownload(urlStr, downloadDir);
	// 如果文件名存在,则进行下载
    if (file.exists()) {
        // 配置文件下载
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        // 下载文件能正常显示中文
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes(), "iso8859-1"));
        // 实现文件下载
        byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            System.out.println("Download the song successfully!");
        } catch (Exception e) {
            System.out.println("Download the song failed!");
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    } else {//对应文件不存在
        try {
            //设置响应的数据类型是html文本,并且告知浏览器,使用UTF-8 来编码。
            response.setContentType("text/html;charset=UTF-8");
            //String这个类里面, getBytes()方法使用的码表,是UTF-8,跟tomcat的默认码表没关系。tomcat iso-8859-1
            String csn = Charset.defaultCharset().name();
            System.out.println("默认的String里面的getBytes方法使用的码表是: " + csn);
            //1. 指定浏览器看这份数据使用的码表
            response.setHeader("Content-Type", "text/html;charset=UTF-8");
            OutputStream os = response.getOutputStream();
            os.write("对应文件不存在".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

总结,代码亲测有效,希望能帮助大家,注意的是我用postman测试,下载下来的文件名有乱码,但在浏览器上能正常显示,不确定是不是postmain的坑。。。。。。

相关标签: java