用于从模式生成URL的Java库

我想知道是否有任何免费的Java库来自动化以下过程:1)一个提供遵循特定模式的URL,例如

http://www.asite.com/path/to/something/thischange/alsothischange-andthischangetoo 

其中一个从上面的字符串中指定:

  • thischange是在[0-10]范围内定义的整数;
  • alsothischange是一个月,然后是集{jan,….,dec};
  • andthischangetoo是在[0-1000]范围内定义的整数;

2)给定模式,库生成所有可能的URL,例如

 http://www.asite.com/path/to/something/0/jan-0 http://www.asite.com/path/to/something/1/jan-0 http://www.asite.com/path/to/something/2/jan-0 ... 

显然,我可以自己开发代码,但如果有可用的东西会更好。

免责声明:我是作者,但……

你可以试试这个库 。 它是RFC 6570(URI模板)的实现。 平心而论,我应该提到存在另一个实现 ,它具有更好的API但更多依赖(我的仅依赖于Guava)。

假设您有变量int1int2month ,您的模板将是:

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

使用该库,您可以执行以下操作:

 // Since the lib depends on Guava, might as well use that final List 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 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)); } 

重要说明: .expand()方法返回String ,而不是URIURL 。 原因是虽然RFC保证了扩展结果,但它不能保证结果字符串实际上是URI或URL。 你必须把这个字符串变成你想要的东西。