package com.ruoyi.common.core.utils;
|
|
import java.io.IOException;
|
import java.io.InputStream;
|
import java.net.HttpURLConnection;
|
import java.net.URL;
|
|
public class UrlDownloader {
|
|
/**
|
* 将指定的URL内容下载为输入流
|
*
|
* @param urlString 要下载的URL
|
* @return 包含URL内容的输入流
|
* @throws IOException 如果发生I/O错误
|
*/
|
public static InputStream downloadAsStream(String urlString) throws IOException {
|
URL url = new URL(urlString);
|
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
connection.setRequestMethod("GET");
|
connection.connect();
|
|
// 检查HTTP响应码
|
int responseCode = connection.getResponseCode();
|
if (responseCode != HttpURLConnection.HTTP_OK) {
|
throw new IOException("HTTP response code: " + responseCode);
|
}
|
|
return connection.getInputStream();
|
}
|
|
public static void main(String[] args) {
|
String urlString = "https://example.com/file.txt"; // 替换为你要下载的URL
|
|
try (InputStream inputStream = downloadAsStream(urlString)) {
|
// 这里你可以处理输入流,例如将其写入文件或进行其他操作
|
byte[] buffer = new byte[1024];
|
int bytesRead;
|
while ((bytesRead = inputStream.read(buffer)) != -1) {
|
// 处理读取的数据,例如写入文件或打印到控制台
|
System.out.write(buffer, 0, bytesRead);
|
}
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
}
|
}
|