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

打印 上一主题 下一主题

主题 862|帖子 862|积分 2586

这个方法将直接处理从URL下载数据并将其生存到文件的整个过程。下面是一个这样的方法示例:
  1. import java.io.FileOutputStream;  
  2. import java.io.IOException;  
  3. import java.io.InputStream;  
  4. import java.io.OutputStream;  
  5. import java.net.HttpURLConnection;  
  6. import java.net.URL;  
  7.   
  8. public class Downloader {  
  9.     public static void downloadAndSave(String urlString, String filePath) {  
  10.         InputStream in = null;  
  11.         try {  
  12.             URL url = new URL(urlString);  
  13.             HttpURLConnection connection = (HttpURLConnection) url.openConnection();  
  14.             connection.setRequestMethod("GET");  
  15.             connection.setUseCaches(false);  
  16.             connection.setRequestProperty("Content-Type", "application/json"); // 或者其他适当的MIME类型,或者根据需求移除  
  17.             connection.setConnectTimeout(60000);  
  18.             connection.setReadTimeout(60000);  
  19.             // 连接服务器  
  20.             connection.connect();  
  21.             // 检查响应码是否为200  
  22.             if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {  
  23.                 in = connection.getInputStream();  
  24.                 // 使用try-with-resources来自动关闭OutputStream  
  25.                 try (OutputStream out = new FileOutputStream(filePath)) {  
  26.                     byte[] buffer = new byte[4096];  
  27.                     int bytesRead;  
  28.                     // 从输入流中读取数据,并写入到文件输出流中  
  29.                     while ((bytesRead = in.read(buffer)) != -1) {  
  30.                         out.write(buffer, 0, bytesRead);  
  31.                     }  
  32.                 }  
  33.                 // 注意:由于使用了try-with-resources,OutputStream会在这里自动关闭  
  34.                 // 但我们仍然需要确保InputStream在方法结束时被关闭  
  35.             } else {  
  36.                 System.out.println("Failed to download file: HTTP error code " + connection.getResponseCode());  
  37.             }  
  38.         } catch (IOException e) {  
  39.             e.printStackTrace();  
  40.         } finally {  
  41.             // 关闭InputStream  
  42.             if (in != null) {  
  43.                 try {  
  44.                     in.close();  
  45.                 } catch (IOException e) {  
  46.                     e.printStackTrace();  
  47.                 }  
  48.             }  
  49.         }  
  50.     }  
  51.     // 示例用法  
  52.     public static void main(String[] args) {  
  53.         String url = "http://example.com/somefile.txt";  
  54.         String filePath = "downloaded_file.txt";  
  55.         downloadAndSave(url, filePath);  
  56.     }  
  57. }
复制代码
在这个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之外,还有其他几种常见的方法。以下是其中两种方法的示例:

  • 使用java.net.URL和java.io.FileOutputStream(简化版,无HttpURLConnection)
    注意:这种方法现实上并不直接支持HTTP哀求的高级功能(如设置哀求头、处理重定向等),但在某些简单的场景下大概足够。对于复杂的HTTP哀求,建议使用HttpURLConnection或更高级的库。
  1. import java.io.FileOutputStream;  
  2. import java.io.IOException;  
  3. import java.io.InputStream;  
  4. import java.net.URL;  
  5.   
  6. public class SimpleDownloader {  
  7.     public static void downloadAndSave(String urlString, String filePath) {  
  8.         try (URL url = new URL(urlString);  
  9.              InputStream in = url.openStream(); // 注意:这里使用的是openStream(),它简化了HTTP GET请求  
  10.              FileOutputStream fos = new FileOutputStream(filePath)) {  
  11.             byte[] buffer = new byte[4096];  
  12.             int bytesRead;  
  13.             while ((bytesRead = in.read(buffer)) != -1) {  
  14.                 fos.write(buffer, 0, bytesRead);  
  15.             }  
  16.         } catch (IOException e) {  
  17.             e.printStackTrace();  
  18.         }  
  19.     }  
  20.   
  21.     public static void main(String[] args) {  
  22.         String url = "http://example.com/somefile.txt";  
  23.         String filePath = "downloaded_file.txt";  
  24.         downloadAndSave(url, filePath);  
  25.     }  
  26. }
复制代码

  • 使用Apache HttpClient库
    Apache HttpClient是一个功能强大的HTTP客户端库,它提供了比HttpURLConnection更丰富的API和更好的机动性。要使用HttpClient,你需要先将其添加到你的项目依赖中。
以下是一个使用Apache HttpClient下载文件的示例:
  1. import org.apache.http.client.methods.HttpGet;  
  2. import org.apache.http.impl.client.CloseableHttpClient;  
  3. import org.apache.http.impl.client.HttpClients;  
  4. import org.apache.http.util.EntityUtils;  
  5.   
  6. import java.io.FileOutputStream;  
  7. import java.io.IOException;  
  8.   
  9. public class HttpClientDownloader {  
  10.   
  11.     public static void downloadAndSave(String urlString, String filePath) {  
  12.         try (CloseableHttpClient httpClient = HttpClients.createDefault();  
  13.             HttpGet httpGet = new HttpGet(urlString);  
  14.             FileOutputStream fos = new FileOutputStream(filePath)) {  
  15.             httpClient.execute(httpGet, httpResponse -> {  
  16.                 try (InputStream inputStream = httpResponse.getEntity().getContent()) {  
  17.                     byte[] buffer = new byte[4096];  
  18.                     int bytesRead;  
  19.                     while ((bytesRead = inputStream.read(buffer)) != -1) {  
  20.                         fos.write(buffer, 0, bytesRead);  
  21.                     }  
  22.                 }  
  23.                 return null; // 这里返回null,因为我们不需要HttpResponse的进一步处理  
  24.             });  
  25.   
  26.         } catch (IOException e) {  
  27.             e.printStackTrace();  
  28.         }  
  29.     }  
  30.   
  31.     // 注意:上面的代码示例使用了HttpClient的异步执行方式(通过execute方法的lambda表达式),  
  32.     // 但这实际上并不是异步的,因为lambda表达式内部是同步执行的。  
  33.     // 对于真正的异步下载,你可能需要使用HttpClient的异步API(如FutureCallback等)。  
  34.   
  35.     // 为了简化,这里提供一个更直接的同步下载示例:  
  36.     public static void downloadAndSaveSync(String urlString, String filePath) throws IOException {  
  37.         try (CloseableHttpClient httpClient = HttpClients.createDefault();  
  38.              HttpGet httpGet = new HttpGet(urlString);  
  39.              FileOutputStream fos = new FileOutputStream(filePath)) {  
  40.   
  41.             CloseableHttpResponse response = httpClient.execute(httpGet);  
  42.             try {  
  43.                 InputStream inputStream = response.getEntity().getContent();  
  44.                 byte[] buffer = new byte[4096];  
  45.                 int bytesRead;  
  46.   
  47.                 while ((bytesRead = inputStream.read(buffer)) != -1) {  
  48.                     fos.write(buffer, 0, bytesRead);  
  49.                 }  
  50.             } finally {  
  51.                 response.close();  
  52.             }  
  53.         }  
  54.     }  
  55.   
  56.     public static void main(String[] args) {  
  57.         String url = "http://example.com/somefile.txt";  
  58.         String filePath = "downloaded_file.txt";  
  59.   
  60.         // 使用同步方法  
  61.         try {  
  62.             downloadAndSaveSync(url, filePath);  
  63.         } catch (IOException e) {  
  64.             e.printStackTrace();  
  65.         }  
  66.     }  
  67. }
复制代码
请注意,上面的downloadAndSave方法现实上并没有以异步方式工作,因为lambda表达式内的代码是同步实行的。我提供了一个名为downloadAndSaveSync的同步方法作为替代,它更直接地展示了如何使用HttpClient进行文件下载。如果你需要真正的异步处理,你应该查看HttpClient的异步API文档。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

正序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

小秦哥

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表