UriBuilder中大括号和空格的编码问题

时间:2018-11-22 16:59:45

标签: java encoding jersey uribuilder

我正在使用com.sun.jersey.api.uri.UriBuilderImpl的{​​{1}}实现来对URL进行编码(版本1.19)。当我的URL的查询参数同时包含大括号和空格时,就会出现此问题。

示例:

UriBuilder

此操作失败,并显示以下信息:

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();

要获得www.something.com?q=%7Bsome%2Bthing%7D,我该怎么做?

2 个答案:

答案 0 :(得分:1)

我正在使用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);

答案 1 :(得分:0)

您可以尝试以下操作: 你需要两个图书馆 jersey-core-1.19.2 javax.ws.rs jersey-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);
    }
}