Java Spring Rest模板未将JSON作为字符串发布

时间:2018-07-05 17:54:33

标签: java spring http spring-rest

我正在尝试使用其Rest API查询ElasticSearch数据库。我正在使用Spring restTemplate在Java中构建客户端。

我首先使用邮递员客户端尝试了该请求,并且工作正常。 例如:

关于邮递员

 Url : http://localhost:9200/index/_search
    Headers: Content-Type : application/json
    Body: Raw
    Body content: {
        "_source": ["_id", "message"],
         "query": {
         "match_all": {}
   }
 }

在Java类中:

  RestTemplate restTemplate = new RestTemplate();

  HttpHeaders headers = new HttpHeaders();

  headers.setContentType(MediaType.APPLICATION_JSON);

  HttpEntity<String> entity = new HttpEntity<String>(input, headers);
  ResponseEntity<String> loginResponse = restTemplate
      .exchange(url, 
  HttpMethod.POST, entity, String.class);

例外是500 Internal Server错误。我能够执行一个简单的get请求,但是在发布请求中发布此json数据时遇到了问题。内部服务器错误的原因可能是什么?

这是控制台上打印的堆栈跟踪。

21:10:59.718 [main] DEBUG org.springframework.web.client.RestTemplate - Created POST request for "http://localhost:9200/index/_search"
21:10:59.738 [main] DEBUG org.springframework.web.client.RestTemplate - Setting request Accept header to [text/plain, */*]
21:10:59.740 [main] DEBUG org.springframework.web.client.RestTemplate - Writing [{"_source": ["_id","message"], "query": {"match_all": {}}] as "application/json" using [org.springframework.http.converter.StringHttpMessageConverter@6522d847]
21:10:59.967 [main] WARN org.springframework.web.client.RestTemplate - POST request for "http://localhost:9200/index/_search" resulted in 500 (Internal Server Error); invoking error handler
org.springframework.web.client.HttpServerErrorException: 500 Internal Server Error
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:71)
    at org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:486)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:443)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:401)
    at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:279)

这是Eclipse调试器提供的图像,它更详细地指示错误。 Eclipse Debugger Stack Trace

0 个答案:

没有答案