浏览器和邮递员返回结果,但由于%26,Rest模板返回0个结果

时间:2019-12-10 06:28:01

标签: java spring resttemplate

在我的网址中有查询部分。在查询中,我通过了%26。 例子

"http://host.com/api/1/searcharticles?key=XXXXXX&query=(subject:"Polls %26 Surveys")"

如果我在Postman或Browser中运行相同的URL,则返回21个结果,但是如果我在RestTemplate中运行,则返回0个结果。 我相信API无法识别%26。

我也在Python中尝试了相同的URL,它返回了21个结果。

示例代码

url = "http://host.com/api/1/searcharticles?key=XXXXXX&query=(subject:"Polls %26 Surveys")";
byte[] gzipResponse = restTemplate.exchange(metabaseUrl, HttpMethod.GET, entity, byte[].class).getBody();
String string = new String(gzipResponse);
System.out.println(string);

3 个答案:

答案 0 :(得分:1)

在使用RestTemplate时,请勿仅将%26用于&尝试使用URLEncoder

URLEncoder.encode(your url string, "UTF-8")

答案 1 :(得分:0)

两件事

第一

您的url变量看起来不正确。应该是

url = "http://host.com/api/1/searcharticles?key=XXXXXX&query=(subject:\"Polls %26 Surveys\")";

第二:

您的网址已编码,因此您需要先对其进行解码,然后再发送

String url = URLDecoder.decode("Polls %26 Surveys", "UTF-8");
System.out.println(url);

OUTPUT:    
Polls & Surveys

答案 2 :(得分:0)

您是否尝试过这种方法,只要在使用之前对网址进行编码,就无需使用%26

    url = "http://host.com/api/1/searcharticles?key=XXXXXX&query=(subject:\"Polls & Surveys\")";
    url = URLEncoder.encode(url, "UTF-8");
    byte[] gzipResponse = restTemplate.exchange(url, HttpMethod.GET, entity, byte[].class).getBody();
    String string = new String(gzipResponse);
    System.out.println(string);