JAVA通过HttpURLConnection实现zip等多种文件的下载

1JAVA通过HttpURLConnection实现zip等多种文件的下载

最近要做一个根据一个http路径的zip文件下载功能,百度很多不实用,最终发现这个亲测可用的代码,分享给大家!话不多说 直接上代码。

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * 下载zip文件
 */
public class DowloadZipUtil {
//urlPath:目标文件路径, downloadDir:下载后要放的文件路径
    public static File downloadFile(String urlPath, String downloadDir) {
        File file = null;
        try {
            // 统一资源
            URL url = new URL(urlPath);
            // 连接类的父类,抽象类
            URLConnection urlConnection = url.openConnection();
            // http的连接类
            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
            // 设定请求的方法,默认是GET
            httpURLConnection.setRequestMethod("GET");
            // 设置字符编码
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            // 打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)。
            httpURLConnection.connect();
            // 文件大小
            int fileLength = httpURLConnection.getContentLength();
            // 文件名
            String filePathUrl = httpURLConnection.getURL().getFile();
            //File.separatorChar代表的是分隔符“/”或者“\”,若详知 自行百度
            String fileFullName = filePathUrl.substring(filePathUrl.lastIndexOf(File.separatorChar) + 1);
            System.out.println("file length---->" + fileLength);
            URLConnection con = url.openConnection();
            BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());
            String path = downloadDir + File.separatorChar + fileFullName;
            file = new File(path);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            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);
                // 打印下载百分比
                // System.out.println("下载了-------> " + len * 100 / fileLength +
                // "%\n");
            }
            bin.close();
            out.close();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            return file;
        }

    }
}

文章来源:链接: http://www.cnblogs.com/h–d/p/5638092.html.

  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要使用JavaHttpURLConnection实现上传多个文件,你可以按以下步骤进行操作: 1. 导入必要的类: ```java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; ``` 2. 创建一个方法来处理文件上传: ```java public void uploadFiles(String url, String[] filePaths) throws IOException { String boundary = "===" + System.currentTimeMillis() + "==="; String lineBreak = "\r\n"; URL uploadUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) uploadUrl.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); OutputStream outputStream = connection.getOutputStream(); for (String filePath : filePaths) { File file = new File(filePath); FileInputStream fileInputStream = new FileInputStream(file); // 写入文件开始分隔符 outputStream.write((lineBreak + "--" + boundary + lineBreak).getBytes()); // 写入Content-Disposition头部信息 outputStream.write(("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"" + lineBreak).getBytes()); outputStream.write(("Content-Type: application/octet-stream" + lineBreak).getBytes()); // 写入空行 outputStream.write(lineBreak.getBytes()); // 写入文件内容 byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = fileInputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } fileInputStream.close(); } // 写入结束分隔符 outputStream.write((lineBreak + "--" + boundary + "--" + lineBreak).getBytes()); outputStream.flush(); outputStream.close(); // 获取响应 int responseCode = connection.getResponseCode(); // 根据需要进行处理响应结果 connection.disconnect(); } ``` 3. 调用`uploadFiles`方法,传入要上传的文件路径和目标URL: ```java String url = "http://example.com/upload"; String[] filePaths = {"/path/to/file1", "/path/to/file2"}; uploadFiles(url, filePaths); ``` 在这个示例中,我们首先创建了一个URL对象,并打开了一个HttpURLConnection。然后,我们设置了请求方法为POST,并设置了Content-Type为multipart/form-data,这是用于上传文件的常用类型。 接下来,我们逐个处理每个文件。我们首先写入文件开始的分隔符,并设置文件的Content-Disposition头部信息。然后,我们写入文件的内容。最后,我们写入文件结束的分隔符。 在写入完所有文件后,我们将输出流刷新并关闭连接。然后,我们可以根据需要处理服务器的响应。 这是一个简单的示例,你可以根据需要进行修改和扩展。确保在实际应用中进行适当的异常处理和错误处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值