Java实现HTTP文件传输

HTTP(HyperText Transfer Protocol,超文本传输协议)是一种用于传输超文本和其他数据的应用层协议。在Web开发中,经常需要通过HTTP协议来传输文件,例如上传文件到服务器或从服务器下载文件。本文将介绍如何使用Java实现HTTP文件传输,包括上传和下载文件。

上传文件

在Java中,可以使用HttpURLConnection类来发送HTTP请求,实现文件上传。以下是一个示例代码,演示了如何上传文件到服务器:

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class FileUploader {
    public static void main(String[] args) {
        String serverUrl = "
        String filePath = "path/to/file.txt";

        try {
            // 创建URL对象
            URL url = new URL(serverUrl);
            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为POST
            connection.setRequestMethod("POST");
            // 允许输入输出流
            connection.setDoInput(true);
            connection.setDoOutput(true);

            // 创建文件输入流
            File file = new File(filePath);
            FileInputStream fileInputStream = new FileInputStream(file);

            // 获取输出流
            OutputStream outputStream = connection.getOutputStream();
            // 设置请求头
            connection.setRequestProperty("Content-Type", "application/octet-stream");
            connection.setRequestProperty("Content-Disposition", "attachment; filename=" + file.getName());

            // 将文件内容写入输出流
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            // 关闭流
            fileInputStream.close();
            outputStream.flush();
            outputStream.close();

            // 获取响应代码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 文件上传成功
                System.out.println("文件上传成功");
            } else {
                // 文件上传失败
                System.out.println("文件上传失败");
            }

            // 断开连接
            connection.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

上述代码中,首先创建了一个URL对象,并打开了与服务器的连接。然后,设置请求方法为POST,并允许输入输出流。接下来,创建了文件输入流,并获取了输出流。在输出流中,设置了请求头,包括文件的MIME类型和文件名。然后,将文件的内容写入输出流,通过outputStream.write(buffer, 0, bytesRead)来实现。最后,关闭流和连接,并根据响应代码判断文件上传是否成功。

下载文件

类似地,使用Java也可以实现从服务器下载文件。以下是一个示例代码,演示了如何从服务器下载文件:

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class FileDownloader {
    public static void main(String[] args) {
        String fileUrl = "
        String savePath = "path/to/save/file.txt";

        try {
            // 创建URL对象
            URL url = new URL(fileUrl);
            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 获取输入流
            InputStream inputStream = connection.getInputStream();
            // 创建文件输出流
            FileOutputStream fileOutputStream = new FileOutputStream(savePath);

            // 将输入流中的内容写入文件输出流
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, bytesRead);
            }

            // 关闭流
            inputStream.close();
            fileOutputStream.flush();
            fileOutputStream.close();

            // 获取响应代码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 文件下载成功
                System.out.println("文件下载成功");
            } else {
                // 文件下载失败
                System.out.println("文件下载失败");
            }

            // 断开连接
            connection.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

上述代码中,同样创建了一个URL对象,并打开了与服务器的连接。通过connection.getInputStream()获取输入流,并创建了文件输出流。然后,将输入流中的内容写入文件输出流。最后,关闭流和连接,并根据响应代码判断文件下载是否成功。

通过上述示例代码,我们可以实现在Java中使用HTTP协议进行文件传输。无论是上传文件到服务器还是从服务器下载文件,都可以通过HttpURLConnection类来