java 使用 Spring MVC 请求后接收 HTTP 状态
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10473067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Receive the HTTP status after a request with Spring MVC
提问by Alex Dowining
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
我正在向服务器发送数据,我想接收 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";
}
采纳答案by erikxiv
The ResponseEntityobject contains the HTTP status code.
该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";
回答by Tomasz Nurkiewicz
What's wrong with:
有什么问题:
HttpStatus status = result.getStatusCode();
if(status == HttpStatus.OK)
See: ResponseEntity
JavaDoc.
请参阅: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.
Java 中的方法名称也倾向于以小写开头。