如何从Java正确编码/提交Elasticsearch查询?

时间:2018-01-06 18:44:28

标签: java elasticsearch spring-boot

在我的Spring Boot应用程序的REST控制器中,我从Node.js应用程序接收GET调用,解析传入的查询字符串,并为Elasticsearch构建查询(v 5.4)

我构建的elasticsearch查询字符串如下所示:

http://34.230.72.180:9200/metadata/_search/?q="*desc*2*"

当我拿这个字符串,并从浏览器或邮递员提交时,我得到了预期的搜索结果。

但是,当我从REST控制器提交完全相同的查询时:

HttpGet getRequest = new HttpGet(
                    finalReq);  //finalReq: http://34.230.72.180:9200/metadata/_search/?q="*desc*2*"
            getRequest.addHeader("accept", "application/json");

            HttpResponse response = httpClient.execute(getRequest);

我收到此错误:

INFO: Initializing Spring FrameworkServlet 'dispatcherServlet'
http://34.230.72.180:9200/metadata/_search/?q="*desc*2*"
Jan 06, 2018 12:33:42 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.IllegalArgumentException: Illegal character in query at index 46: http://34.230.72.180:9200/metadata/_search/?q="*desc*2*"] with root cause
java.net.URISyntaxException: Illegal character in query at index 46: http://34.230.72.180:9200/metadata/_search/?q="*desc*2*"
    at java.net.URI$Parser.fail(URI.java:2848)
    at java.net.URI$Parser.checkChars(URI.java:3021)
    at java.net.URI$Parser.parseHierarchical(URI.java:3111)
    at java.net.URI$Parser.parse(URI.java:3053)
    at java.net.URI.<init>(URI.java:588)
    at java.net.URI.create(URI.java:850)

我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

您应该对您的网址参数进行编码:

url = "http://34.230.72.180:9200/metadata/_search/?q=" + URLEncoder.encode("\"*desc*2*\"", "UTF-8");

价:

Encoding URL query parameters in Java

http://www.avajava.com/tutorials/lessons/how-do-i-encode-url-parameters.html

http://www.baeldung.com/java-url-encoding-decoding