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

标签 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

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

最佳答案

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/

相关文章:

java - JPA查询: java. lang.ClassCastException : [Enum] cannot be cast to java. lang.Enum

java - 新的 SimpleDateFormat ("hh:mm a", Locale.getDefault()).parse ("04:30 PM")给出 Unparseable 异常

WCF:URI 的注册已存在

javascript - 我从哪里获得 http ://jsfiddle.net/jrweinb/MQ6VT/中提到的 javascript uri css

java - 包含路径的 URI 模板变量?

java - Spring 和 AMQP RabbitMQ 主题交换不起作用

java - 使用 Junit 进行 Jersey Restful 测试

Android 如何从已知的 URI 获取单首歌曲的 ID 信息

java - 一个 URI 模板形式的路径变量数量不受限制

c# - 如何使用 WebHttpBinding 在 WCF 的 uri 路径中使用强类型参数