如何使用 URI 模板更改 URL in java 中的路径参数

how to use URI templates to change path parameters in a URL in java

我按照 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 地图一起使用。