HttpURLConnection下载文件

本文介绍了如何通过HttpURLConnection调用文件服务并实现文件下载,包括处理请求URL中的中文路径、编码以及检查HTTP响应码以确保文件下载成功。
摘要由CSDN通过智能技术生成

 通过HttpURLConnection调用文件服务,实现文件下载,直接cv就能使用的文件下载。

  public  void downloadFile(DownloadUrl downloadUrl,HttpServletRequest request) throws IOException ,UnsupportedEncodingException{
        try {
        URL s = new URL(request.getRequestURL().toString());
        String serverAddress = s.getProtocol() + "://" + s.getHost() + ":" + s.getPort()+"/";
        String url1 = downloadUrl.getUrl();
        String encodedUrl = URLEncoder.encode(url1, StandardCharsets.UTF_8.toString());
        String path=serverAddress+encodedUrl;
        //String filePath = path.replace("\\", "/");
            String saveDir = "你下载到本地的地址";
            File saveDirFile = new File(saveDir);
            if (!saveDirFile.exists()) {
                saveDirFile.mkdirs();
            }
           // String encode = URLEncoder.encode(filePath,"UTF-8");
            //String decode = URLDecoder.decode(encode, "UTF-8");
            URL url = new URL(path);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            int responseCode = httpConn.getResponseCode();
            // 检查HTTP响应码
            if (responseCode == HttpURLConnection.HTTP_OK) {
                String disposition = httpConn.getHeaderField("Content-Disposition");
                String fileName = "";
                if (disposition != null) {
                    int index = disposition.indexOf("filename=");
                    if (index > 0) {
                        fileName = disposition.substring(index + 10, disposition.length() - 1);
                    }
                } else {
                    fileName = path.substring(path.lastIndexOf("/") + 1);
                }
                // 从URL连接获取输入流
               try(InputStream inputStream = httpConn.getInputStream();
                // 打开一个文件输出流
                FileOutputStream outputStream = new FileOutputStream(saveDir + File.separator + fileName)) {
                   int bytesRead;
                   byte[] buffer = new byte[4096];
                   while ((bytesRead = inputStream.read(buffer)) != -1) {
                       outputStream.write(buffer, 0, bytesRead);
                   }
                   outputStream.close();
                   inputStream.close();
                   System.out.println("文件下载完成");
               }
            } else {
                System.out.println("文件下载失败. 响应码: " + responseCode);
            }
            httpConn.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

如果你的返回值不是void ,可能就会报错 同时使用了getOutputStream()和getWriter()。

如果传的文件路径是带有中文的,那么就会报错,需要进行编码;

String encode = URLEncoder.encode(name,"UTF-8");
 String encodedUrl =url1.replace(name,encode);

最后下载下来的文件名需要在filename的地方通过传的url去切割。

  • 12
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值