Ayelet
Ayelet

Reputation: 1743

Java SFTP (apache vfs2) - password with @

I'm trying to use the org.apache.commons.vfs2 to download a file via SFTP. The problem is, the password contains the '@' char, so this causes the URI to be parsed incorrectly:

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

Does anyone has an idea how to get around this issue? (I can't change the password, obviously). This is the code I'm using:

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

Upvotes: 5

Views: 4485

Answers (2)

Ryan
Ryan

Reputation: 1

You need to encode the your password by UriParser.encode(), you can change your code like below:

you code:

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

change to:

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

Hope it help, thank you.

Upvotes: 0

Kenster
Kenster

Reputation: 25438

Use an actual URI constructor instead of hand-rolling your own:

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

Upvotes: 6

Related Questions