Java library to generate URLs from a pattern

后端 未结 1 741
南笙
南笙 2021-01-29 13:22

I want to know if there is any free Java library to automate the following process: 1) One provides an URL that follows a specific pattern, e.g.

http://www.asite         


        
相关标签:
1条回答
  • 2021-01-29 14:02

    Disclaimer: I am the author, but...

    You can try this library. It is an implementation of RFC 6570 (URI templates). In all fairness, I should mention that there exists another implementation, which has a nicer API but a lot more dependencies (mine only depends on Guava).

    Let's say you have variables int1, int2, month, your template would be:

    http://www.asite.com/path/to/something/{int1}/{month}-{int2}
    

    Using the library, you can do something like this:

    // Since the lib depends on Guava, might as well use that
    final List<String> months = ImmutableList.of("jan", "feb", "etc");
    
    // Create the template
    final URITemplate template 
        = new URITemplate("http://www.asite.com/path/to/something/{int1}/{month}-{int2}");
    
    // Variable values
    VariableValue int1, month, int2;
    
    // Expansion data
    Map<String, VariableValue> data;
    
    // Build the strings
    for (int i1 = 0; i1 <= 10; i1++)
        for (final String s: months)
            for (int i2 = 0; i2 <= 1000; i2++) {
                int1 = new ScalarValue(Integer.toString(i1));
                month = new ScalarValue(s);
                int2 = new ScalarValue(Integer.toString(i2));
                data = ImmutableMap.of("int1", int1, "month", month, "int2", int2);
                // Print the template
                System.out.println(template.expand(data));
            }
    

    IMPORTANT NOTE: the .expand() method returns a String, not a URI or a URL. The reason is that while the RFC guarantees expansion results, it cannot guarantee that the resulting string is actually a URI or URL. You'll have to turn that string into what you want by yourself.

    0 讨论(0)
提交回复
热议问题