0

I have a String like

String input = "grant_type=client_credentials&scope=complexScope";

and I'd like to parse and then add these request parameters to a List of NameValuePair of Apache commons.

I have created this function, which technically works through String splits.

public static  List<NameValuePair> stringToNameValuePair(String input) {
return Arrays.stream(input.split("&"))
        .map(pair -> new NameValuePair(pair.split("=")[0], pair.split("=")[1]))
        .collect(Collectors.toList());
}

which seems to do the job for simple things, but I wonder if there is something already built-in and more tested in java or in any known library.

Leo
  • 1,829
  • 4
  • 27
  • 51
  • Does this answer: https://stackoverflow.com/a/13592567/2478398 give you an appropriate method without a library. If you want to use a library, `spring-web` provides `UriComponentsBuilder` which would return a `MultiValueMap` using `UriComponentsBuilder.fromUriString("?a=b&c=d").build().getQueryParams();` – BeUndead May 02 '21 at 01:07
  • @BeUndead it is close, thanks. in this case I do not have the whole URL, I could use the solutions listed there by appending a URL. – Leo May 02 '21 at 01:21
  • 1
    It looks like you could just skip to the bit with `query = url.getQuery();` part, and use your `input` variable in that's place through the rest of the method calls. – BeUndead May 02 '21 at 01:24
  • 1
    It also appears you're trying to reimplement OAuth2, which you should _also_ be using a library (or entire stack) for. – chrylis -cautiouslyoptimistic- May 02 '21 at 01:28
  • @chrylis-cautiouslyoptimistic- yeah.. it is not what it seems...... – Leo May 02 '21 at 02:51

0 Answers0