【问题标题】:Java SFTP (apache vfs2) - password with @Java SFTP (apache vfs2) - 带@的密码
【发布时间】:2014-10-19 13:15:33
【问题描述】:

我正在尝试使用 org.apache.commons.vfs2 通过 SFTP 下载文件。 问题是,密码包含“@”字符,所以这会导致 URI 被错误地解析:

org.apache.commons.vfs2.FileSystemException: Expecting / to follow the hostname in URI

有人知道如何解决这个问题吗? (显然,我无法更改密码)。这是我正在使用的代码:

String sftpUri = "sftp://" + userName + ":" + password + "@"
        + remoteServerAddress + "/" + remoteDirectory + fileName;

String filepath = localDirectory + fileName;
File file = new File(filepath);
FileObject localFile = manager.resolveFile(file.getAbsolutePath());

FileObject remoteFile = manager.resolveFile(sftpUri, opts);
localFile.copyFrom(remoteFile, Selectors.SELECT_SELF);

【问题讨论】:

  • 再看看你的sftpUri。如果您的密码包含@,remoteServerAddress 参数会发生什么情况?
  • 正如我所说,我知道问题出在哪里(由于密码中的@,URI 解析不正确)。我的问题是如何解决它。
  • 对不起。我没看到。看看stackoverflow.com/questions/6718471/…
  • 这可能是一个愚蠢的问题,但是如何对密码进行编码?
  • 您可以使用来自java.netURLEncoder.encode(...)。只对用户名和密码进行编码。

标签: java sftp apache-commons-vfs


【解决方案1】:

使用an actual URI constructor 而不是自己手动滚动:

String userInfo = userName + ":" + password;
String path = remoteDirectory + filename;  // Need a '/' between them?
URI sftpUri = new URI("sftp", userInfo, remoteServerAddress, -1, path, null, null);
...
FileObject remoteFile = manager.resolveFile(sftpUri.toString(), opts);

【讨论】:

  • 并确保路径以 / 开头并且不使用 windows \ 字符。或者你从这样的文件转换它:new File("c:\\temp").toURI().getPath()
猜你喜欢
  • 2015-04-10
  • 1970-01-01
  • 2014-09-23
  • 1970-01-01
  • 2021-08-28
  • 1970-01-01
  • 2019-04-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多