请求在curl中工作但不在RestTemplate中工作

时间:2017-06-21 15:03:48

标签: spring curl resttemplate

curl中的以下调用正在运行,服务器响应是200代码:

curl -i -H "Content-Type: application/json" -H "Cookie: wv_sess=emrri58a7f3qauof5ntfsc77k7" -X GET http://192.168.1.1/cli/aos?cmd=show+interfaces+1/1/1

但是当我尝试使用以下代码在Spring中使用RestTemplate时:

        String cookies = "wv_sess=emrri58a7f3qauof5ntfsc77k7";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.set("Cookie",cookies);
        headers.set("Content-Type",MediaType.APPLICATION_JSON_VALUE);

        HttpEntity<String> entity = new HttpEntity<>(headers);
        ResponseEntity<String> response = restTemplate.exchange("http://192.168.1.1/cli/aos?cmd=show+interfaces+1/1/1", HttpMethod.GET, entity, String.class);

        logger.info(response.toString());

我得到一个400代码,所以它使HttpClient崩溃:

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.client.HttpClientErrorException: 400 Bad Request] with root cause

从curl句子到RestTemplate的等价物是什么? 有人有任何建议要解决它吗?

注意:我从Alcatel 6860交换机向Web服务发出请求。

2 个答案:

答案 0 :(得分:0)

从你的错误:

nested exception is 
org.springframework.web.client.HttpClientErrorException: 400 Bad Request

看起来您的请求正在通过,服务器正在响应400 Bad Request。只要服务器返回4xx错误代码,Spring RestTemplate就会抛出HttpClientErrorException

答案 1 :(得分:0)

我找到了解决方案,无论如何都要感谢回复。

问题是RestTemplate正在编码我的网址,我是通过Wireshark检测到的。

鉴于原始网址:

http://192.168.1.1/cli/aos?cmd=show+interfaces+1/1/1

它被替换为“+”符号,结果如下:

http://192.168.1.1/cli/aos?cmd=show%2Binterfaces%2B1/1/1

因此服务器当然检测到无效的URL并且必须回答400代码错误。

要修复它,我将符号“+”替换为编码为“+”的空格。

相关问题