Windows的图片通过sftp传输到Linux服务器上面
pom.xml
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.70</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.netbeans.external</groupId>
<artifactId>com-jcraft-jsch</artifactId>
<version>RELEASE220</version>
</dependency>
主类
private static final String SERVER_HOST = "目标主机IP地址";
private static final String USERNAME = "用户名";
private static final String PASSWORD = "密码";
private static final int PORT = 22; // 默认SSH端口
public static void main(String[] args) {
JSch jsch = new JSch();
Session session = null;
try {
session = jsch.getSession(USERNAME, SERVER_HOST, PORT);
session.setPassword(PASSWORD);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
String url = "https://www.baidu.com/aaa.png"; // 替换为实际的 URL
String remoteFilePath = "/home//aaa.png";//目标服务器路径
downloadAndSaveToSFTP(url, remoteFilePath, sftpChannel);
sftpChannel.disconnect();
System.out.println("File transferred successfully.");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (session != null && session.isConnected()) {
session.disconnect();
}
}
}
public static void downloadAndSaveToSFTP(String url, String remoteFilePath, ChannelSftp sftpChannel) throws Exception {
URL httpUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
conn.setUseCaches(false); // 设置不要缓存
conn.setInstanceFollowRedirects(true);
conn.setDoInput(true); // 设置是否从httpUrlConnection读入
conn.setConnectTimeout(30000); // 设置超时时间
conn.setReadTimeout(30000);
// 发起GET请求
conn.setRequestMethod("GET");
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { // 成功
InputStream inputStream = conn.getInputStream();
sftpChannel.put(inputStream, remoteFilePath, ChannelSftp.OVERWRITE);
} else {
throw new Exception("Failed : HTTP error code : " + responseCode);
}
}