Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove a query parameter from a query string

Tags:

java

I am using UriBuilder to remove a parameter from a URI:

public static URI removeParameterFromURI(URI uri, String param) {
    UriBuilder uriBuilder = UriBuilder.fromUri(uri);
    return uriBuilder.replaceQueryParam(param, "").build();
}

public static String removeParameterFromURIString(String uriString, String param) {
    try {
        URI uri = removeParameterFromURI(new URI(uriString), param);
        return uri.toString();
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
}

The above sort of works and modifies:

http://a.b.c/d/e/f?foo=1&bar=2&zar=3

… into:

http://a.b.c/d/e/f?bar=&foo=1&zar=3

But it has the following issues:

  1. It messes up the order of the parameters. I know that the order is not relevant but it still bothers me.
  2. it doesn't fully remove the parameter, it just sets its value to the empty string. I would prefer is the parameter is completely removed from the query string.

Is there some standard or commonly used library that can achieve the above neatly without having to parse and hack the query string myself?

like image 467
Marcus Junius Brutus Avatar asked Dec 09 '16 15:12

Marcus Junius Brutus


2 Answers

In Android, without import any library. I write a util method inspired by this answerReplace query parameters in Uri.Builder in Android?(Replace query parameters in Uri.Builder in Android?)

Hope can help you. Code below:

public static Uri removeUriParameter(Uri uri, String key) {
    final Set<String> params = uri.getQueryParameterNames();
    final Uri.Builder newUri = uri.buildUpon().clearQuery();
    for (String param : params) {
        if (!param.equals(key)) {
            newUri.appendQueryParameter(param, uri.getQueryParameter(param));
        }
    }
    return newUri.build();
}
like image 82
TTKatrina Avatar answered Sep 26 '22 03:09

TTKatrina


If you are on Android and want to remove all query parameters, you can use

Uri uriWithoutQuery = Uri.parse(urlWithQuery).buildUpon().clearQuery().build();

like image 28
Daniel F Avatar answered Sep 25 '22 03:09

Daniel F