AbuMariam
AbuMariam

Reputation: 3678

Handling URLs which have '@' for java.net.URI getUserInfo

I have a string where a FTP URL is defined, and I want to parse the username and password details out of that string. For that I am using the getUserInfo method of java.net.URI (https://docs.oracle.com/javase/6/docs/api/java/net/URI.html)...

 def userInfo = uri.getUserInfo()
 def username
 def password

   if(userInfo){
      def pos = userInfo.indexOf(":")
      if(pos >= 0){
          username = userInfo.substring(0, pos)
          password = userInfo.substring(pos+1)
   }    
 }   

This code works fine except if the URL has a '@' in it like this..

 ftp://[email protected]:[email protected]/orders.txt

For a URL like this, a call to uri.getUserInfo() returns null.

Is there any way to handle such URLs?

Upvotes: 2

Views: 1762

Answers (1)

rdmueller
rdmueller

Reputation: 11052

A @ is not a valid character in a username or password in a URL. It has to be encoded. So your code will work if you write the URI like this:

ftp://kirk%40starfleetcom:spock123@enterprisecom/orders.txt

afaik, you should simply url-encode both username and password before you construct the URI:

java.net.URLEncoder.encode(username)

Upvotes: 1

Related Questions