在JAX-RS中的查询参数中转义`%`符号

问题描述 投票:0回答:1

我尝试使用Jersey或Resteasy中的任何一个发送带有一些URL字符串作为参数的GET请求

Response response = new ResteasyClientBuilder()
        .build()
        .target(UriBuilder.fromPath("https://foo.bar"))
        .queryParam("url", "http://hostname.com/The%20URL%20with spaces.jpg")
        .request()
        .get();

两种实现都发送 https://foo.bar?url=http%3A%2F%2Fhostname.com%2FThe%20URL%20with%20spaces.jpg

我假设原始空间用%20转义,原始%20在查询参数中被双重转义。 但事实并非如此。 原始空间和%20是混合的,在服务器端我得到未转义的字符串,所有%20转换为空格,字符串被破坏。

根据source code of Resteasy,它“保持编码值”%......“和模板参数完整”。但是我没有在JEE文档中找到任何关于这种行为的词。

在将其添加为参数之前,我应该逃避我的字符串吗? 我应该使用什么来逃避它以确保它逃脱所有的"%..." and template parameters,并且在服务器中成功解除参与其中的一个参数逃脱?

java escaping jax-rs resteasy jersey-client
1个回答
1
投票

标准JAX-RS WebTarget的解决方案是不直接应用参数,而是将它们用作模板参数。

Response response = new ResteasyClientBuilder()
        .build()
        .target(UriBuilder.fromPath("https://foo.bar"))
        .queryParam("url", "{urlTemplate}")
        .resolveTemplate("urlTemplate", "http://hostname.com/The%20URL%20with spaces.jpg")
        .request()
        .get();

首先,我们添加一些模板{urlTemplate}作为参数值,然后使用实际值渲染此模板。 WebTarget始终假定给定参数作为可能的模板,并且不会转义某些字符 但.resolveTemplate()保证逃脱应该逃脱的所有角色

© www.soinside.com 2019 - 2024. All rights reserved.