我遵循了 here 中提供的教程用给定值替换路径参数并运行下面给出的示例代码
import org.glassfish.jersey.uri.UriTemplate;
import javax.ws.rs.core.UriBuilder;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
public class Demo {
public static void main(String[] args) {
String template = "http://example.com/name/{name}/age/{age}";
UriTemplate uriTemplate = new UriTemplate(template);
String uri = "http://example.com/name/Bob/age/47";
Map<String, String> parameters = new HashMap<>();
// Not this method returns false if the URI doesn't match, ignored
// for the purposes of the this blog.
uriTemplate.match(uri, parameters);
System.out.println(parameters);
parameters.put("name","Arnold");
parameters.put("age","110");
UriBuilder builder = UriBuilder.fromPath(template);
URI output = builder.build(parameters);
System.out.println(output.toASCIIString());
}
}
但是当我编译代码时它给了我这个错误
Exception in thread "main" java.lang.IllegalArgumentException: The template variable 'age' has no value
请帮我解决这个问题,(可能是我的导入导致了这个问题)
最佳答案
public static void main(String[] args) {
String template = "http://example.com/name/{name}/age/{age}";
UriTemplate uriTemplate = new UriTemplate(template);
String uri = "http://example.com/name/Bob/age/47";
Map<String, String> parameters = new HashMap<>();
// Not this method returns false if the URI doesn't match, ignored
// for the purposes of the this blog.
uriTemplate.match(uri, parameters);
System.out.println(parameters);
parameters.put("name","Arnold");
parameters.put("age","110");
UriBuilder builder = UriBuilder.fromPath(template);
// Use .buildFromMap()
URI output = builder.buildFromMap(parameters);
System.out.println(output.toASCIIString());
}
如果您使用 .build
填充模板,则必须像 .build("Arnold", "110")
一样一个一个地提供值。在您的情况下,您希望将 .buildFromMap()
与您的 parameters
map 一起使用。
关于java - 如何使用 URI 模板更改 Java 中 URL 中的路径参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43653780/