Java通过GET请求保存文件

在使用Java进行网络编程时,我们经常需要通过GET请求从服务器上获取文件并保存到本地。本文将介绍如何使用Java进行GET请求并将响应保存为文件。

1. 使用URLConnection发送GET请求

Java提供了URLConnection类来处理网络请求。我们可以使用它来发送GET请求并获取服务器的响应。

首先,我们需要创建一个URL对象,并将要请求的URL作为参数传递给它。然后,我们可以使用openConnection()方法打开一个连接,并将其强制转换为HttpURLConnection。

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class FileDownloader {
    public static void main(String[] args) {
        String fileUrl = " // 要下载的文件的URL
        String savePath = "/path/to/save/file.pdf"; // 保存文件的路径

        try {
            URL url = new URL(fileUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedInputStream inputStream = new BufferedInputStream(connection.getInputStream());
                FileOutputStream outputStream = new FileOutputStream(savePath);

                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }

                outputStream.close();
                inputStream.close();
            } else {
                System.out.println("请求失败,响应码:" + responseCode);
            }

            connection.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2. 获取文件的保存路径和文件名

在上面的示例中,我们将文件保存到固定的路径(savePath)下,并将其命名为file.pdf。如果我们希望自动获取文件的保存路径和文件名,可以使用URLConnection的getHeaderField()方法获取Content-Disposition头字段中的信息。

...

int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
    String contentDisposition = connection.getHeaderField("Content-Disposition");
    String savePath = getSavePath(contentDisposition); // 获取保存路径
    String filename = getFilename(contentDisposition); // 获取文件名

    BufferedInputStream inputStream = new BufferedInputStream(connection.getInputStream());
    FileOutputStream outputStream = new FileOutputStream(savePath + filename);

    ...
}
...

private static String getSavePath(String contentDisposition) {
    String savePath = "/path/to/save/"; // 默认保存路径

    if (contentDisposition != null) {
        String[] parts = contentDisposition.split(";");
        for (String part : parts) {
            if (part.trim().startsWith("filename=")) {
                String filename = part.substring(part.indexOf('=') + 1).trim().replace("\"", "");
                savePath = savePath + filename.substring(0, filename.lastIndexOf('/') + 1);
                break;
            }
        }
    }

    return savePath;
}

private static String getFilename(String contentDisposition) {
    String filename = "file.pdf"; // 默认文件名

    if (contentDisposition != null) {
        String[] parts = contentDisposition.split(";");
        for (String part : parts) {
            if (part.trim().startsWith("filename=")) {
                filename = part.substring(part.indexOf('=') + 1).trim().replace("\"", "");
                break;
            }
        }
    }

    return filename;
}

3. 完整示例代码解析

在上面的示例代码中,我们首先创建一个URL对象,并将文件的URL作为参数传递给它。然后,我们使用openConnection()方法打开一个连接,并将其转换为HttpURLConnection对象。

我们设置请求方法为GET,并获取服务器的响应码。如果响应码为HTTP_OK(即200),则表示请求成功。我们可以使用connection.getInputStream()获取服务器的响应数据流,并使用BufferedInputStream进行缓冲。然后,我们创建一个FileOutputStream对象,并使用循环读取响应数据并写入到本地文件中。

最后,我们关闭输入流和输出流,并断开与服务器的连接。

4. 总结

通过上面的示例代码,我们学习了如何使用Java发送GET请求并将响应保存为文件。我们还介绍了如何获取文件的保存路径和文件名。希望这篇文章对你有所帮助!