7

我按照此处提供的教程用给定值替换路径参数并运行下面给出的示例代码

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

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

4

1 回答 1

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

于 2017-04-27T10:18:39.217 回答