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

时间:2017-04-27 09:24:07

标签: java uri uritemplate url-template

我按照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

请帮我解决这个问题,(可能是我的导入导致问题)

1 个答案:

答案 0 :(得分:5)

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