简体   繁体   English

如何避免转义 WebTarget 查询参数?

[英]How can I avoid escaping a WebTarget query parameter?

I want to turn off URL encoding for Jersey requests, or for certain parameters.我想关闭 Jersey 请求或某些参数的 URL 编码。

The server I'm talking to requires the format of example.com/path?query=foo:bar我正在与之交谈的服务器需要example.com/path?query=foo:bar的格式

With Jackson WebTarget,使用 Jackson WebTarget,

final WebTarget target = ClientBuilder.newClient()
    .target(url)
    .queryParam("query", "{queryVal}")
    .resolveTemplate("queryVal", "foo:bar");

Sadly this produces example.com/path?query=foo bar which is not accepted by the server.遗憾的是,这会产生服务器不接受的example.com/path?query=foo bar

I've searched a lot for this and the only promising avenue seems to be something to do with javax.ws.rs.core.Configuration , but I haven't gotten far with that yet.我为此搜索了很多,唯一有希望的途径似乎与javax.ws.rs.core.Configuration ,但我还没有深入了解。

I figured it out: The solution is to use a request filter as documented in Advanced Features of the Client API我想通了:解决方案是使用 客户端 API 的高级功能中记录的请求过滤器

final WebTarget target = ClientBuilder.newClient()
    .target(url)
    .queryParam("query", "{queryVal}")
    .resolveTemplate("queryVal", "foo:bar")
    .register(Filter.class)

and then we have然后我们有

@Provider
public class Filter implements ClientRequestFilter {
    private static final Logger logger = LoggerFactory.getLogger(Filter.class);

    @Override
    public void filter(ClientRequestContext ctx) throws IOException {
        try {
            logger.debug("Before: {}", ctx.getUri());
            //this is gonna get ugly
            ctx.setUri(new URI(
                URLDecoder.decode(ctx.getUri().toString(), StandardCharsets.UTF_8.toString())));
            logger.debug("After: {}", ctx.getUri());
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }
}

Output:输出:

com.example.client.Filter : Before: http://example.com/path?query=foo%3Abar
com.example.client.Filter : After: http://example.com/path?query=foo:bar

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM