在SpringBoot中处理REST服务

时间:2017-09-22 05:11:29

标签: java spring rest spring-boot resttemplate

我有以下代码用于POST JSON对象到以下URL

        HttpEntity messageEntity = new HttpEntity(message, buildHttpHeaders(getTerminalId()));
        String theUrl = "http://123.433.234.12/receive";
        try {
               System.out.println("In try block");
               ResponseEntity<Dto> responseEntity= restTemplate.exchange(theUrl, HttpMethod.POST, messageEntity, Dto.class);
          } catch (HttpStatusCodeException ex) {
              // get http status code
          }

如果URL无效或服务不可用,我希望它抛出错误状态代码,如404或503.不幸的是,它总是停在try块。有没有办法解决这个问题?

输出

In try block

修改

 String theUrl = "http://123.433.234.12/receive" + transactionId; //invalid Id
   try {
          System.out.println("=========start=========");
          ResponseEntity<Dto> responseEntity= restTemplate.exchange(theUrl, HttpMethod.POST, messageEntity, Dto.class);
          System.out.println("=========end=========");
       } catch (HttpStatusCodeException ex) {
          String a = ex.getStatusCode().toString();
          System.out.println(a);
    }

输出

=========start=========
2017-09-22 14:54:54 [xles-server-ThreadPool.PooledThread-0-running] ERROR c.r.abc.jpos.JposRequestListener - Error HttpStatusCode 500org.springframework.web.client.HttpServerErrorException: 500 null

它停止并且不会在========end ========

中显示catch或任何状态代码

有效网址

   http://abc0/receive/hello

如果我改为

 http://abc0/recei/hello

我会在catch块中得到404,看起来很好。但是当我改为另一个不退出的网址时,例如

 http://123.433.234.12/receive

它在try block中。为什么????

2 个答案:

答案 0 :(得分:1)

参考this doc,您应该抓住RestClientException而不只是HttpStatusCodeException

如果你想在特定场景中抛出异常,可以这样做

    try {
        restTemplate.exchange(...);
    }
    catch (RestClientException e) {
        // implies error is related to i/o. 
        if (e instanceof ResourceAccessException) {
            // java.net.ConnectException will be wrapped in e with message "Connection timed out".
            if (e.contains(ConnectException.class)) {
                // handle connection timeout excp
            }
        } else if (e instanceof HttpClientErrorException) {
            // Handle all HTTP 4xx error codes here;

        } else if (e instanceof HttpServerErrorException) {
            // Handle all HTTP 5xx error codes here
        }
    }

对于HttpClientErrorException,您可以从excption获取错误代码,如下所示

HttpClientErrorException clientExcp = (HttpClientErrorException) e;
HttpStatus statusCode = clientExcp.getStatusCode();

同样聪明,您可能会收到HttpServerErrorException的错误代码。

答案 1 :(得分:1)

据我记得RestTemplate.exchange方法抛出RestClientException。您的catch子句中有HttpStatusCodeException,它只是RestClientException个子类中的一个。 您尝试访问的地址(http://123.433.234.12/receive)不是有效地址,因此您无法获得任何响应(无200秒但无500秒或400秒)。尝试捕获RestClientException并打印其消息以查看发生了什么。然后你可以编写一些代码来管理这种情况。

此外,如果这不起作用,请尝试逐步进行检查,并确认ResponseEntity为空,以及它在身体中的含义。这是我在尝试理解某种方法时所做的事情; =)