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

news/2024/10/11 2:47:01/
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/news/1537228.html

相关文章

一篇文章入门MySQL数据库

目录 配置环境 下载 安装 登录 本地登录​ 远程登录 用户管理 用户增删查 查询用户 新增用户 删除用户 用户密码管理 重命名用户 用户权限管理 赋权 撤权 查看权限 数据类型 数值型 日期时间型 字符串型 show显示语句 查询数据库 查询数据表 其他用法…

Java之方法

方法&#xff08;函数&#xff09; Java中的方法必须定义在类或接口中。 package day2;import java.util.Scanner;public class way {public static void main(String[] args) {int arr[] new int[5];Scanner sc new Scanner(System.in);for (int i 0; i < arr.length;…

5个免费ppt模板网站推荐!轻松搞定职场ppt制作!

每次过完小长假&#xff0c;可以明显地感觉到&#xff0c;2024这一年很快又要结束了&#xff0c;不知此刻的你有何感想呢&#xff1f;是满载而归&#xff0c;还是准备着手制作年终总结ppt或年度汇报ppt呢&#xff1f; 每当说到制作ppt&#xff0c;很多人的第一反应&#xff0c…

大模型笔记05--coze经典案例分析

大模型笔记05--coze经典案例分析 介绍经典案例分析抖音视频转小红书文案艺术照 & 卡通照片助手艺术照图像流卡通照片图像流多功能图像助手 注意事项说明 介绍 扣子是新一代 AI 应用开发平台&#xff0c;具备完善的生态系统&#xff0c;是国内最出色的AI平台之一。用好coze…

C语言 | 第十三章 | 二维数组 冒泡排序 字符串指针 断点调试

P 120 数组应用案例 2023/1/29 一、应用案例 案例一&#xff1a;创建一个char类型的26个元素的数组&#xff0c;分别 放置’A’-Z‘。使用for循环访问所有元素并打印出来。提示&#xff1a;字符数据运算 ‘A’1 -> ‘B’ #include<stdio.h>void main(){/*创建一个c…

Linux云计算 |【第四阶段】RDBMS1-DAY5

主要内容&#xff1a; 试图概述&#xff08;创建视图VIEW、修改、查看、删除&#xff09;、变量&#xff08;全局变量、会话变量、用户变量、局部变量&#xff09;、存储过程&#xff08;创建、调用、删除存储过程&#xff09;、流程控制结构&#xff08;分支结构&#xff1a;…

蓝桥杯【物联网】零基础到国奖之路:十二. TIM

蓝桥杯【物联网】零基础到国奖之路:十二. TIM 第一节 理论知识第二节 cubemx配置 第一节 理论知识 STM32L071xx器件包括4个通用定时器、1个低功耗定时器&#xff08;LPTIM&#xff09;、2个基本定时器、2个看门狗定时器和SysTick定时器。 通用定时器&#xff08;TIM2、TIM3、…

vue3常用组件通信方法

title: vue3常用组件通信方法 date: 2024-10-06 15:00:54 tags: vue3 组件通信 一、父传子—defineProps 1.父亲 通过属性传值 2.儿子 通过defineProps接收相关的数据 二、子传父 1&#xff09;使用defineExposeref 1.子组件 在子组件中使用defineExpose先暴露出来 2.父…