UriBuilder 中大括号和 space 的编码问题

Encoding issue with curly brackets and space in UriBuilder

我正在使用 UriBuildercom.sun.jersey.api.uri.UriBuilderImpl 实现来编码 URL(版本 1.19)。当我的 URL 的查询参数同时包含大括号和 space.

时,就会出现问题

示例:

UriBuilder uriBuilder = fromUri("www.something.com")
        .queryParam("q", "{some thing}");

return uriBuilder.build().toString();

这失败了:

javax.ws.rs.core.UriBuilderException: java.net.URISyntaxException: Illegal character in query at index 27: www.something.com?q=%7Bsome thing%7D

有趣的是,如果我去掉大括号,我得到了预期的编码:www.something.com?q=some+thing...

org.apache.http.client.utils.URIBuilder 编码如我所料,即:www.something.com?q=%7Bsome+thing%7D

我试过这样做:

...
.queryParam("q", UriComponent.encode(searchQuery, UriComponent.Type.QUERY_PARAM)).
.build();

但是 space 字符也被编码为 www.something.com?q=%7Bsome%2Bthing%7D

我需要做什么才能得到 www.something.com?q=%7Bsome+thing%7D

我正在使用 jersey-client v1.9.1 和您的代码 运行,没有任何错误。

这是我的 Maven 依赖项:

<!-- https://mvnrepository.com/artifact/com.sun.jersey/jersey-client -->
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-client</artifactId>
            <version>1.9.1</version>
        </dependency>

和 java 代码:

import java.net.URI;

import javax.ws.rs.core.UriBuilder;

public class Main {
    public static void main(String[] args) throws Exception {
        try {
            URI url = UriBuilder.fromUri("www.something.com")
                    .queryParam("q", "{some thing}")
                    .build();
            System.out.println(url);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

输出:www.something.com?q=%7Bsome+thing%7D

更新

花括号是 v1.19 失败的原因(参见 the documentation

这是 v1.19 的工作版本:

        URI url = UriBuilder.fromPath("www.something.com")
                .queryParam("q", "{value}")
                .build("{some thing}", "value");
        System.out.println(url);

你可以试试这个: 你需要两个库 jersey-core-1.19.2javax.ws.rsjersey-client-1.19.2

public class ClassTest {
    public static void main(String[] args) throws UnsupportedEncodingException {
        String queryString =  URLEncoder.encode("{some thing}", "UTF-8");
        System.out.println(queryString);
        URI uri = UriBuilder.fromUri("www.something.com")
                .queryParam("q", queryString)
                .build();
        String url = uri.toString().replace("%2B", "+");
        System.out.println(url);
    }
}