44

I have URL string like:

"http://www.xyz/path1/path2/path3?param1=value1&param2=value2".

I need to get this url without parameters, so the result should be:

"http://www.xyz/path1/path2/path3".

I have done it this way:

private String getUrlWithoutParameters(String url)
{
  return url.substring(0,url.lastIndexOf('?'));
}

Are there any better ways to do it?

Eran
  • 387,369
  • 54
  • 702
  • 768
Maksym
  • 4,434
  • 4
  • 27
  • 46

7 Answers7

75

Probably not the most efficient way, but more type safe :

private String getUrlWithoutParameters(String url) throws URISyntaxException {
    URI uri = new URI(url);
    return new URI(uri.getScheme(),
                   uri.getAuthority(),
                   uri.getPath(),
                   null, // Ignore the query part of the input url
                   uri.getFragment()).toString();
}
Abdul Wasae
  • 3,614
  • 4
  • 34
  • 56
Eran
  • 387,369
  • 54
  • 702
  • 768
  • 7
    Use the right tool for the job rather than focusing on micro-optimizations with manual string meddling - the only correct answer IMO. – Gimby Dec 03 '14 at 09:09
  • 1
    But the difference is quite huge, indexof+substring 55 times faster , but not so safe. So if you need performance you need to use indexof+substring if not then you should more care about safety. – Maksym Dec 03 '14 at 09:22
  • I'm no URI expert, but at first glance I'd assume that this approach could change the meaning of the URI and NOT reproduce one with the same semantics (besides the omitted URI part). E.g. a percent-encoded colon in the authority part will have been decoded to a plain colon in the new URL. So `bla%3Abla@example.com` will be represented as `bla:bla@example.com` in the new URL - is this the same thing, according to the RfCs? I couldn't find an authorative (no pun intended) answer immediately, but would interpret the first one as "user 'bla:bla', no password", the second one as "user bla, pw bla". – Gunter Ohrner Oct 27 '19 at 13:36
  • This approach definitely does not work for URIs containing query Strings, which are however explicitly omitted here. But if you use the same approach to also transfer the query part, it will change all encoded `&`s appearing in data values into actual `&`s, inventing new keys and values. This could even be a security risk. – Gunter Ohrner Oct 27 '19 at 13:38
  • 1
    Doesn't work with jdbc urls – caeus Aug 16 '23 at 19:56
23

I normally use

url.split("\\?")[0]
PbxMan
  • 7,525
  • 1
  • 36
  • 40
10

Using javax.ws.rs.core.UriBuilder from JAX-RS 2.0:

UriBuilder.fromUri("https://www.google.co.nz/search?q=test").replaceQuery(null).build();

Using the very similar org.springframework.web.util.UriBuilder from Spring:

UriComponentsBuilder.fromUriString("https://www.google.co.nz/search?q=test").replaceQuery(null).build(Collections.emptyMap());
Adrian Baker
  • 9,297
  • 1
  • 26
  • 22
  • 1
    For Jakarta EE 10: https://javadoc.io/static/jakarta.platform/jakarta.jakartaee-api/10.0.0/jakarta/ws/rs/core/UriBuilder.html#replaceQuery(java.lang.String) – gouessej Mar 27 '23 at 14:48
4

You can use org.apache.http.client.utils.URIBuilder from httpclient jar

@Test
void test_removeQueryParameters() throws Exception {
    String url = "http://www.google.com?query=Shanghai&foo=bar";
    String expectedUrl = "http://www.google.com";

    String result = removeQueryParameters(url);
    Assert.assertThat(result, equalTo(expectedUrl));
}

public String removeQueryParameters(String url) throws URISyntaxException {
    URIBuilder uriBuilder = new URIBuilder(url);
    uriBuilder.removeQuery();

    return uriBuilder.build().toString();
}
sendon1982
  • 9,982
  • 61
  • 44
3

You could use something like the following, that removes the query part from the URL.

private String getUrlWithoutParameters(String url) throws MalformedURLException {
    return url.replace(new URL(url).getQuery(), "");
}

Alternatively, you might want to check if url rewrite covers your needs: http://tuckey.org/urlrewrite/

dchar
  • 1,665
  • 2
  • 19
  • 28
2

With an URL it could be done by methods. With a String:

url = url.replaceFirst("\\?.*$", "");

This attempts to replace all starting with a question mark. When no question mark, the original string is kept.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
1

Try using substring and indexOf method in String:

String str = "http://www.xyz/path1/path2/path3?param1=value1&param2=value2";
int index = str.indexOf("?");
if (index != -1) {
    System.out.println(str.substring(0, str.indexOf("?")));
} else {
    System.out.println("You dont have question mark in your url");
}
SMA
  • 36,381
  • 8
  • 49
  • 73
  • yeah, I did it exactly the same way, do you think it's the best way to do it? – Maksym Dec 03 '14 at 08:51
  • mine is better, if "?" is not there you get an index out of rage – PbxMan Dec 03 '14 at 08:52
  • There is always a tradeoff between space and time. I think with split you will end up creating two different object if you encounter "?". Also split treats split pattern as regex which is not needed in your case and hence i think split would be overhead. – SMA Dec 03 '14 at 08:59
  • I wrote test and seems like I have the most faster one :) – Maksym Dec 03 '14 at 09:08
  • I would agree with the same. Just see i updated the answer to be more robust code. – SMA Dec 03 '14 at 09:10