免责声明:我是作者,但是...
你可以试试这个图书馆 https://github.com/fge/uri-template。它是 RFC 6570(URI 模板)的实现。平心而论,我应该提到的是,存在另一个实现 https://github.com/damnhandy/Handy-URI-Templates,它有一个更好的 API,但有更多的依赖项(我的仅依赖于 Guava)。
假设你有变量int1
, int2
, month
,您的模板将是:
http://www.asite.com/path/to/something/{int1}/{month}-{int2}
使用该库,您可以执行以下操作:
// 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));
}
重要提示:.expand()
方法返回一个String
, not a URI
or a URL
。原因是,虽然 RFC 保证扩展结果,但它不能保证结果字符串实际上是 URI 或 URL。您必须自己将该字符串变成您想要的内容。