You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot能否调用FTP API下载PDF文件,可否使用RestTemplate实现

FTP账单PDF获取方案说明

能否使用RestTemplate调用该FTP接口?

不可以。RestTemplate是Spring封装的HTTP请求工具,底层默认依赖HTTP客户端实现,仅支持HTTP/HTTPS协议,原生不支持FTP协议,因此无法直接通过RestTemplate请求该FTP URL获取PDF文件。

具体实现方案

推荐使用Apache Commons Net提供的FTPClient实现,轻量且兼容性强,实现步骤如下:

1. 引入依赖

在项目pom.xml中添加以下依赖:

<dependency>
    <groupId>commons-net</groupId>
    <artifactId>commons-net</artifactId>
    <version>3.9.0</version>
</dependency>

2. 核心代码实现

可以封装为工具类,也可以注册为Spring Bean使用,FTP配置建议提取到application.yml等配置文件中通过@Value注入,避免硬编码:

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class FtpBillService {

    @Value("${ftp.host:10.60.1.140}")
    private String ftpHost;
    @Value("${ftp.port:21}")
    private Integer ftpPort;
    @Value("${ftp.username:phoneApp}")
    private String ftpUsername;
    @Value("${ftp.password:phoneApp}")
    private String ftpPassword;

    /**
     * 根据手机号获取FTP上的账单PDF文件
     * @param mobileNumber 用户输入的手机号
     * @return PDF字节数组,获取失败返回null
     */
    public byte[] getPdfByMobile(String mobileNumber) {
        FTPClient ftpClient = new FTPClient();
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            // 连接FTP服务器
            ftpClient.connect(ftpHost, ftpPort);
            // 登录校验
            if (!ftpClient.login(ftpUsername, ftpPassword)) {
                return null;
            }
            // 开启被动模式,适配防火墙策略
            ftpClient.enterLocalPassiveMode();
            // 设置二进制传输模式,避免PDF文件损坏
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            // 拼接目标文件名
            String targetFileName = mobileNumber + ".pdf";
            // 下载文件
            if (ftpClient.retrieveFile(targetFileName, outputStream)) {
                return outputStream.toByteArray();
            }
            ftpClient.logout();
        } catch (IOException e) {
            // 可根据业务需要自定义异常处理逻辑
            e.printStackTrace();
        } finally {
            // 断开连接,避免连接泄漏
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}

3. 注意事项

  • 如果PDF文件不在FTP根目录,需要在登录后添加ftpClient.changeWorkingDirectory("目标目录路径")切换工作目录
  • 需要确保应用服务器网络可以连通FTP服务器的21端口,以及FTP被动模式对应的端口范围

方案可行性说明

该方案是Java生态中处理FTP请求的通用成熟方案,经过大量生产场景验证,稳定性、兼容性都有保障,可以满足业务需求。

内容的提问来源于stack exchange,提问作者J. Doe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 06:33:04