Parse a URI String into Name-Value Collection

前端 未结 19 2523
难免孤独
难免孤独 2020-11-22 01:34

I\'ve got the URI like this:

https://google.com.ua/oauth/authorize?client_id=SS&response_type=code&scope=N_FULL&access_type=offline&redirect_         


        
19条回答
  •  星月不相逢
    2020-11-22 01:54

    Netty also provides a nice query string parser called QueryStringDecoder. In one line of code, it can parse the URL in the question. I like because it doesn't require catching or throwing java.net.MalformedURLException.

    In one line:

    Map> parameters = new QueryStringDecoder(url).parameters();
    

    See javadocs here: https://netty.io/4.1/api/io/netty/handler/codec/http/QueryStringDecoder.html

    Here is a short, self contained, correct example:

    import io.netty.handler.codec.http.QueryStringDecoder;
    import org.apache.commons.lang3.StringUtils;
    
    import java.util.List;
    import java.util.Map;
    
    public class UrlParse {
    
      public static void main(String... args) {
        String url = "https://google.com.ua/oauth/authorize?client_id=SS&response_type=code&scope=N_FULL&access_type=offline&redirect_uri=http://localhost/Callback";
        QueryStringDecoder decoder = new QueryStringDecoder(url);
        Map> parameters = decoder.parameters();
        print(parameters);
      }
    
      private static void print(final Map> parameters) {
        System.out.println("NAME               VALUE");
        System.out.println("------------------------");
        parameters.forEach((key, values) ->
            values.forEach(val ->
                System.out.println(StringUtils.rightPad(key, 19) + val)));
      }
    }
    

    which generates

    NAME               VALUE
    ------------------------
    client_id          SS
    response_type      code
    scope              N_FULL
    access_type        offline
    redirect_uri       http://localhost/Callback
    

提交回复
热议问题