java http下载到本地文件

@Api(tags = "文件")
@RestController
@RequestMapping("/file")
public class FileUpload {

    @GetMapping("/downloadFile")
    public void updateUploadStatus() throws IOException {
        String fileName = "index.html";//文件名带格式
        String filePath = "C:\\Users\\Administrator\\Desktop\\test\\";
        String utlFilepath = "https://bxwell.oss-cn-beijing.aliyuncs.com/userInfo/54b35024-1f90-4916-990d-cf29bea53d6c/index.html";
        URL url = new URL(utlFilepath);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod(con.getRequestMethod());
        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        con.setRequestProperty("User-Agent", "Mozilla/4.76");
        con.setRequestProperty("connection", "keep-alive");
        con.setDoOutput(true);
        BufferedInputStream out = new BufferedInputStream(con.getInputStream());
        File file = new File(filePath+fileName);
        file.createNewFile();
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath+fileName));
        try {
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = out.read(bufferOut)) != -1) {
                bos.write(bufferOut, 0, bytes);
            }
        } catch (Exception e) {
            throw e;
        } finally {
            out.close();
            bos.close();
        }
    }
}
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以帮你解答这个问题。你可以使用 JavaHttpURLConnection 类来发送 HTTP GET 请求并下载文件到本地。下面是一个简单的示例代码: ```java import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class HttpDownload { public static void main(String[] args) throws Exception { URL url = new URL("http://example.com/file.zip"); // 文件下载链接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); InputStream inputStream = conn.getInputStream(); FileOutputStream outputStream = new FileOutputStream("file.zip"); // 本地保存的文件名 byte[] buffer = new byte[4096]; int len; while ((len = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } outputStream.close(); inputStream.close(); conn.disconnect(); } } ``` 在这个示例中,我们首先创建一个 URL 对象,指定要下载文件的链接。然后使用 HttpURLConnection 类打开连接,并设置请求方法为 GET。接下来,我们获取输入流并创建一个本地文件输出流。使用一个缓冲区来读取输入流中的数据,并将其写入输出流中,直到输入流结束。最后,关闭所有流,断开连接。 请注意,这只是一个简单的示例,实际应用中你可能需要处理更多的异常和错误情况。另外,你可能还需要设置一些请求头或参数来正确处理下载请求。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值