Receive the HTTP status after a request with Spring MVC

社会主义新天地 提交于 2019-12-19 20:23:12

问题


i'm sending data to a server and i want to receive the HTTP response status in order to check this status and provide the appropriate view

   @RequestMapping(method = RequestMethod.POST)
     public String Login(@ModelAttribute("Attribute") Login login, Model model,HttpServletRequest request) {

          // Prepare acceptable media type
          ArrayList<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
          acceptableMediaTypes.add(MediaType.APPLICATION_XML);

          // Prepare header
          HttpHeaders headers = new HttpHeaders();
          headers.setAccept(acceptableMediaTypes);

          HttpEntity<Login> entity = new HttpEntity<Login>(login, headers);

          // Send the request as POST
          try {
           ResponseEntity<Login> result = restTemplate.exchange("http://www.../user/login/", 
                   HttpMethod.POST, entity, Login.class);
          } catch (Exception e) {
          }
      //here i want to check the received status
      if(status=="OK"){
         return "login"
      }
      else          
      return "redirect:/home";
     }

回答1:


The ResponseEntity object contains the HTTP status code.

// Prepare acceptable media type
ArrayList<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
acceptableMediaTypes.add(MediaType.APPLICATION_XML);

// Prepare header
HttpHeaders headers = new HttpHeaders();
headers.setAccept(acceptableMediaTypes);

HttpEntity<Login> entity = new HttpEntity<Login>(login, headers);
// Create status variable outside of try-catch block
HttpStatus statusCode = null;

// Send the request as POST
try {
  ResponseEntity<Login> result = restTemplate.exchange("http://www.../user/login/", 
  HttpMethod.POST, entity, Login.class);
  // Retrieve status code from ResponseEntity
  statusCode = result.getStatusCode();
} catch (Exception e) {
}
// Check if status code is OK
if (statusCode == HttpStatus.OK) {
  return "login"
}
else          
  return "redirect:/home";



回答2:


What's wrong with:

HttpStatus status = result.getStatusCode();
if(status == HttpStatus.OK)

See: ResponseEntity JavaDoc.

BTW you should not compare strings using == operator like here:

status=="OK"

Instead use the following idiom:

"OK".equals(status)

Also method names in Java tend to start with lower case.



来源:https://stackoverflow.com/questions/10473067/receive-the-http-status-after-a-request-with-spring-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!