Java SFTP(apache vfs2)-带@的密码



我正试图使用org.apache.mons.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);

使用实际的URI构造函数,而不是手动滚动自己的:

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);

您需要通过UriParser.encode()对密码进行编码,您可以更改如下代码:

您的代码:

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

更改为:

String sftpUri = "sftp://" + userName + ":" + **UriParser.encode(password, "@".toCharArray())**+ "@"
        + remoteServerAddress + "/" + remoteDirectory + fileName;

希望有帮助,谢谢。

相关内容

  • 没有找到相关文章

最新更新