Springboo通过http请求下载文件到服务器

devtools/2024/10/11 3:16:20/
http://www.w3.org/2000/svg" style="display: none;">

这个方法将直接处理从URL下载数据并将其保存到文件的整个过程。下面是一个这样的方法示例:

import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.InputStream;  
import java.io.OutputStream;  
import java.net.HttpURLConnection;  
import java.net.URL;  public class Downloader {  public static void downloadAndSave(String urlString, String filePath) {  InputStream in = null;  try {  URL url = new URL(urlString);  HttpURLConnection connection = (HttpURLConnection) url.openConnection();  connection.setRequestMethod("GET");  connection.setUseCaches(false);  connection.setRequestProperty("Content-Type", "application/json"); // 或者其他适当的MIME类型,或者根据需求移除  connection.setConnectTimeout(60000);  connection.setReadTimeout(60000);  // 连接服务器  connection.connect();  // 检查响应码是否为200  if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {  in = connection.getInputStream();  // 使用try-with-resources来自动关闭OutputStream  try (OutputStream out = new FileOutputStream(filePath)) {  byte[] buffer = new byte[4096];  int bytesRead;  // 从输入流中读取数据,并写入到文件输出流中  while ((bytesRead = in.read(buffer)) != -1) {  out.write(buffer, 0, bytesRead);  }  }  // 注意:由于使用了try-with-resources,OutputStream会在这里自动关闭  // 但我们仍然需要确保InputStream在方法结束时被关闭  } else {  System.out.println("Failed to download file: HTTP error code " + connection.getResponseCode());  }  } catch (IOException e) {  e.printStackTrace();  } finally {  // 关闭InputStream  if (in != null) {  try {  in.close();  } catch (IOException e) {  e.printStackTrace();  }  }  }  }  // 示例用法  public static void main(String[] args) {  String url = "http://example.com/somefile.txt";  String filePath = "downloaded_file.txt";  downloadAndSave(url, filePath);  }  
}

在这个downloadAndSave方法中,我们首先尝试从给定的URL下载数据。如果HTTP响应码为200(OK),我们就从连接中获取InputStream,并使用try-with-resources语句来自动关闭FileOutputStream,同时将数据从InputStream写入到文件中。无论操作成功与否,我们都会在finally块中关闭InputStream,以确保资源被正确释放。

请注意,我修改了setRequestProperty的键从"Charset"到"Content-Type",但通常对于GET请求来说,设置"Content-Type"并不是必需的,因为它是由请求体(对于GET请求来说,请求体是空的)的媒体类型决定的。然而,如果你正在向服务器发送POST或PUT请求,并包含请求体,那么设置正确的"Content-Type"就非常重要了。在这个例子中,我保留了它,但你可能想要根据实际需求进行调整或移除它。如果你只是想从服务器下载文件,那么通常不需要设置"Content-Type"。

实现文件下载并保存的功能,除了使用HttpURLConnection之外,还有其他几种常见的方法。以下是其中两种方法的示例:

  1. 使用java.net.URL和java.io.FileOutputStream(简化版,无HttpURLConnection)
    注意:这种方法实际上并不直接支持HTTP请求的高级功能(如设置请求头、处理重定向等),但在某些简单的场景下可能足够。对于复杂的HTTP请求,建议使用HttpURLConnection或更高级的库。
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.InputStream;  
import java.net.URL;  public class SimpleDownloader {  public static void downloadAndSave(String urlString, String filePath) {  try (URL url = new URL(urlString);  InputStream in = url.openStream(); // 注意:这里使用的是openStream(),它简化了HTTP GET请求  FileOutputStream fos = new FileOutputStream(filePath)) {  byte[] buffer = new byte[4096];  int bytesRead;  while ((bytesRead = in.read(buffer)) != -1) {  fos.write(buffer, 0, bytesRead);  }  } catch (IOException e) {  e.printStackTrace();  }  }  public static void main(String[] args) {  String url = "http://example.com/somefile.txt";  String filePath = "downloaded_file.txt";  downloadAndSave(url, filePath);  }  
}
  1. 使用Apache HttpClient库
    Apache HttpClient是一个功能强大的HTTP客户端库,它提供了比HttpURLConnection更丰富的API和更好的灵活性。要使用HttpClient,你需要先将其添加到你的项目依赖中。

以下是一个使用Apache HttpClient下载文件的示例:

import org.apache.http.client.methods.HttpGet;  
import org.apache.http.impl.client.CloseableHttpClient;  
import org.apache.http.impl.client.HttpClients;  
import org.apache.http.util.EntityUtils;  import java.io.FileOutputStream;  
import java.io.IOException;  public class HttpClientDownloader {  public static void downloadAndSave(String urlString, String filePath) {  try (CloseableHttpClient httpClient = HttpClients.createDefault();  HttpGet httpGet = new HttpGet(urlString);  FileOutputStream fos = new FileOutputStream(filePath)) {  httpClient.execute(httpGet, httpResponse -> {  try (InputStream inputStream = httpResponse.getEntity().getContent()) {  byte[] buffer = new byte[4096];  int bytesRead;  while ((bytesRead = inputStream.read(buffer)) != -1) {  fos.write(buffer, 0, bytesRead);  }  }  return null; // 这里返回null,因为我们不需要HttpResponse的进一步处理  });  } catch (IOException e) {  e.printStackTrace();  }  }  // 注意:上面的代码示例使用了HttpClient的异步执行方式(通过execute方法的lambda表达式),  // 但这实际上并不是异步的,因为lambda表达式内部是同步执行的。  // 对于真正的异步下载,你可能需要使用HttpClient的异步API(如FutureCallback等)。  // 为了简化,这里提供一个更直接的同步下载示例:  public static void downloadAndSaveSync(String urlString, String filePath) throws IOException {  try (CloseableHttpClient httpClient = HttpClients.createDefault();  HttpGet httpGet = new HttpGet(urlString);  FileOutputStream fos = new FileOutputStream(filePath)) {  CloseableHttpResponse response = httpClient.execute(httpGet);  try {  InputStream inputStream = response.getEntity().getContent();  byte[] buffer = new byte[4096];  int bytesRead;  while ((bytesRead = inputStream.read(buffer)) != -1) {  fos.write(buffer, 0, bytesRead);  }  } finally {  response.close();  }  }  }  public static void main(String[] args) {  String url = "http://example.com/somefile.txt";  String filePath = "downloaded_file.txt";  // 使用同步方法  try {  downloadAndSaveSync(url, filePath);  } catch (IOException e) {  e.printStackTrace();  }  }  
}

请注意,上面的downloadAndSave方法实际上并没有以异步方式工作,因为lambda表达式内的代码是同步执行的。我提供了一个名为downloadAndSaveSync的同步方法作为替代,它更直接地展示了如何使用HttpClient进行文件下载。如果你需要真正的异步处理,你应该查看HttpClient的异步API文档。


http://www.ppmy.cn/devtools/123950.html

相关文章

Python知识点:如何使用Raspberry Pi与Python进行边缘计算

开篇,先说一个好消息,截止到2025年1月1日前,翻到文末找到我,赠送定制版的开题报告和任务书,先到先得!过期不候! 如何使用Raspberry Pi与Python进行边缘计算 Raspberry Pi是一款广受欢迎的小型单…

代码随想录算法训练营第四十六天 | 647. 回文子串,516.最长回文子序列

四十六天打卡,今天用动态规划解决回文问题,回文问题需要用二维dp解决 647.回文子串 题目链接 解题思路 没做出来,布尔类型的dp[i][j]:表示区间范围[i,j] (注意是左闭右闭)的子串是否是回文子串&#xff0…

TikTok点赞被取消的原因分析与解决办法

随着TikTok的快速发展,越来越多的人和品牌将其视为推广和营销的重要平台。然而,用户在使用过程中,可能会遇到点赞被取消的情况,这不仅影响用户的使用体验,还可能对内容创作者的影响力和品牌形象产生负面影响。本文将深…

AAA Redis的过期删除策略+缓存雪崩+缓存一致性问题

目录 一、三种删除策略比较 二、缓存雪崩缓存击穿缓存穿透 三、缓存一致性 Redis学习笔记 一、三种删除策略比较 内存占用CPU占用特征定时删除节约内存,无占用不分时段占用CPU资源,频度高时间换空间惰性删除内存占用严重延时执行,CPU利用…

electron-vite_1搭建项目

脚手架选型,electron-vite;Electron开发构建工具基于Vite的;目前项目是使用Vite写的所以用这个集成比较快;目前他们也有提供vue和react的模板; 基于 Vite,快速、简单且功能强大 框架连接 electron-vite 目…

Leetcode—763. 划分字母区间【中等】

2024每日刷题&#xff08;175&#xff09; Leetcode—763. 划分字母区间 C实现代码 class Solution { public:vector<int> partitionLabels(string s) {int rightmost[26];int l 0;int r 0;for(int i 0; i < s.length(); i) {rightmost[s[i] - a] i;}vector<…

【MySQL 08】复合查询

目录 1.准备工作 2.多表查询 笛卡尔积 多表查询案例 3. 自连接 4.子查询 1.单行子查询 2.多行子查询 3.多列子查询 4.在from子句中使用子查询 5.合并查询 1.union 2.union all 1.准备工作 如下三个表&#xff0c;将作为示例&#xff0c;理解复合查询 EMP员工表…

Python 工具库每日推荐 【Pandas】

文章目录 引言Python数据处理库的重要性今日推荐:Pandas工具库主要功能:使用场景:安装与配置快速上手示例代码代码解释实际应用案例案例:销售数据分析案例分析高级特性数据合并和连接时间序列处理数据透视表扩展阅读与资源优缺点分析优点:缺点:总结【 已更新完 TypeScrip…