Reputation: 1
I'm working with JAX-RS in Java. I need to get from the UriInfo the relative path of the URI, i.e. the URI without the scheme and authority parts but with path and query parameters. What is the best way to do it?
Upvotes: 0
Views: 5269
Reputation: 355
I needed the exact same thing although few years later. Nevertheless here's how.
URI requestURI = this.uriInfo.getRequestUri();
URI baseUri = this.uriInfo.getBaseUri();
URI uri = baseUri.relativize(requestURI);
Upvotes: 1
Reputation: 3191
check this:
String uri = "http://google.com/path?q1=va";
int index = -1;
if ((index = uri.indexOf("://")) > 0) {
uri = uri.substring(index + 3);
}
index = uri.indexOf('/');
uri = uri.substring(index);
System.out.println(uri);
or like this:
URI uri = new URI("http://google.com/path?q1=va");
System.out.println(uri.getPath()+"?"+uri.getQuery());
Upvotes: 0
Reputation: 1508
According to https://jsr311.java.net/nonav/javadoc/javax/ws/rs/core/UriInfo.html if you call
getPath()
You will "Get the path of the current request relative to the base URI as a string."
Upvotes: 1
Reputation: 1692
String sourceUrl = "http://www.example.com/mysite/whatever/somefolder/bar/unsecure!+?#whätyöühäv€it/site.html"; // your current site
String targetUrl = "http://www.example.com/mysite/whatever/otherfolder/other.html"; // the link target
String expectedTarget = "../../../otherfolder/other.html";
String[] sourceElements = sourceUrl.split("/");
String[] targetElements = targetUrl.split("/"); // keep in mind that the arrays are of different length!
StringBuilder uniquePart = new StringBuilder();
StringBuilder relativePart = new StringBuilder();
boolean stillSame = true;
for(int ii = 0; ii < sourceElements.length || ii < targetElements.length; ii++) {
if(ii < targetElements.length && ii < sourceElements.length &&
stillSame && sourceElements[ii].equals(targetElements[ii]) && stillSame) continue;
stillSame = false;
if(targetElements.length > ii)
uniquePart.append("/").append(targetElements[ii]);
if(sourceElements.length > ii +1)
relativePart.append("../");
}
String result = relativePart.toString().substring(0, relativePart.length() -1) + uniquePart.toString();
System.out.println("result: " + result);
Upvotes: 0