I am trying to create a java.net.URI (for use with spring RestTemplate) but I'm given a FULL url and I need to correctly encode things.
Every example I see online, including using the Spring UriComponentsBuilder assumes that you have the URL and you have the parameters separate. So then they encode the URI and add parameters.
If I feed my full string value of the url (which includes all of the arguments) to the builder, it encodes the arguments as well in a way that is incorrect. For example, it converted an = to &.
For example, I'm given this as a starting point:
https://graph.microsoft.com/v1.0/users?$select=signInActivity,accountEnabled,userPrincipalName,userType,manager&$expand=manager($select=userPrincipalName)&$filter=(accountEnabled eq true)
If I just naively feed it to the UriComponentsBuilder and say build with encoding:
String url = "https://graph.microsoft.com/v1.0/users?$select=signInActivity,accountEnabled,userPrincipalName,userType,manager&$expand=manager($select=userPrincipalName)&$filter=(accountEnabled eq true)"
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url);
UriComponents uricomp = builder.build(false);
URI uri = uricomp.toUri();
I get this:
https://graph.microsoft.com/v1.0/users?$select=signInActivity,accountEnabled,userPrincipalName,userType,manager&$expand=manager($select&userPrincipalName)&$filter=(accountEnabled%20eq%20true)
which is not correct, note the ($select&userPrincipalName).
I get I could just parse the original full url string on the ? and then split on every & and = sign to break things up. That would be a lot of custom String split and I would probably miss something.
Does anyone know a better/correct way to do this? I can't really get the user to provide arguments. It's kinda like how you paste a URL into postman and it automagically breaks out and shows the arguments, probably by doing a split.
You would think there some library or some way to feed the full string and have it encode correctly, but can't find it. Any ideas? Thank you!
https://graph.microsoft.com/v1.0/users?$select=signInActivity,accountEnabled,userPrincipalName,userType,manager&$expand=manager($select=userPrincipalName)&$filter=(accountEnabled%20eq%20true)new URI(url)and forget about Spring altogether. In this case, you could donew URI(url.replace(" ", "%20")), but that doesn’t solve the general problem. If the source of your URI is generating URIs by just blindly concatenating strings, there may be no way to safely accomplish your goal.