Receive the HTTP status after a request with Spring MVC

前端 未结 2 1592
醉酒成梦
醉酒成梦 2021-01-19 11:41

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

   @RequestMappin         


        
2条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-19 12:32

    The ResponseEntity object contains the HTTP status code.

    // Prepare acceptable media type
    ArrayList acceptableMediaTypes = new ArrayList();
    acceptableMediaTypes.add(MediaType.APPLICATION_XML);
    
    // Prepare header
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(acceptableMediaTypes);
    
    HttpEntity entity = new HttpEntity(login, headers);
    // Create status variable outside of try-catch block
    HttpStatus statusCode = null;
    
    // Send the request as POST
    try {
      ResponseEntity 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";
    

提交回复
热议问题