4

我正在向服务器发送数据,并且我想接收 HTTP 响应状态以检查此状态并提供适当的视图

   @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";
     }
4

2 回答 2

5

有什么问题:

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

请参阅:ResponseEntityJavaDoc。

顺便说一句,您不应使用==此处的运算符比较字符串:

status=="OK"

而是使用以下成语:

"OK".equals(status)

Java中的方法名称也倾向于以小写字母开头。

于 2012-05-06T18:51:14.543 回答
4

ResponseEntity对象包含 HTTP 状态代码。

// 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";
于 2012-05-06T18:50:09.737 回答