Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a Param in QueryString in Java

lets say I have a url param like token=1234235asdjaklj231k209a&name=sam&firname=Mahan how can I replace the value of the token with new one ? I've done something similar to this with pattern and matcher before but I don't recall now but I know there is a way to do so Update : the token can contain any letter but & thanks in advance

like image 274
Mahan Avatar asked Oct 16 '25 23:10

Mahan


2 Answers

Spring has a util that handles this need gracefully. Apache httpcomponents does too. Below is a spring example.

import org.springframework.web.util.UriComponentsBuilder;
import java.net.URI;


public class StackOverflow {

  private static class SO46303058 {
    public static void main(String[] args) {
      final String urlString = "https://subdomain.hostname/path/resource?token=1234235asdjaklj231k209a&name=sam&firname=Mahan";
      final URI uri = UriComponentsBuilder.fromHttpUrl(urlString)
          .replaceQueryParam("token", "abc")
          .build().toUri();
      System.out.println(uri);
    }
  }
}

Don't be afraid of adding dependencies to your project, it beats reinventing the wheel.

like image 121
Andreas Avatar answered Oct 18 '25 13:10

Andreas


We can consider doing a simple regex replacement, with a few caveats (q.v. below the code snippet).

String url = "token=1234235asdjaklj231k209a&name=sam&firname=Mahan";
url = url.replaceFirst("\\btoken=.*?(&|$)", "token=new_value$1");
System.out.println(url);
url = "param1=value&token=1234235asdjaklj231k209a";
url = url.replaceFirst("\\btoken=.*?(&|$)", "token=new_value$1");
System.out.println(url);

Edge cases to consider are first that your token may be the last parameter in the query string. To cover this case, we should check for token=... ending in either an ambersand & or the end of the string. But if we don't use a lookahead, and instead consume that ambersand, we have to also add it back in the replacement. The other edge case, correctly caught by @DodgyCodeException in his comment below, is that there be another query parameter which just happens to end in token. To make sure we are really matching our token parameter, we can preface it with a word boundary in the regex, i.e. use \btoken=... to refer to it.

Output:

token=new_value&name=sam&firname=Mahan
param1=value&token=new_value
like image 27
Tim Biegeleisen Avatar answered Oct 18 '25 13:10

Tim Biegeleisen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!