从Spring REST API返回HTTP代码200

时间:2018-08-07 20:40:05

标签: java spring spring-boot

我想使用此代码来接收带有值的http链接:

@PostMapping(value = "/v1/notification")
public String handleNotifications(@RequestParam("notification") String itemid) {
    // parse here the values
    return "result successful result";
}

如何返回http代码200-成功的响应?

例如,如果在代码处理中存在代码异常,我该如何返回错误404

4 个答案:

答案 0 :(得分:5)

如果您使用@RestConroller,则默认情况下应返回200。

但是无论如何,您可以通过@ResponseStatus注释设置特定的响应状态(即使方法返回void),也可以通过ResponseEntity返回自定义响应。

编辑:添加错误处理

对于错误处理,您可以返回特定的响应实体

 return ResponseEntity.status(HttpStatus.FORBIDDEN)
            .body("some body ");

或者您可以使用@ExceptionHandler

   @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public void handleError(Exception ex) {
        // TODO: log exception
    }

答案 1 :(得分:4)

如果您正在使用spring:

 @PostMapping(value = "/v1/notification")
public ResponseEntity handleNotifications(@RequestParam("notification") String itemid) {
    // parse here the values
    return ResponseEntity.ok().build(); //OR ResponseEntity.ok("body goes heare");
}

答案 2 :(得分:2)

您可以通过使用@ResponseStatusHttpStatus.OK注释方法来做到这一点(但是默认情况下应为200),就像这样:

某些控制器

@PostMapping(value = "/v1/notification")
@ResponseStatus(HttpStatus.OK)
public String handleNotifications(@RequestParam("notification") String itemid) throws MyException {
    if(someCondition) {
       throw new MyException("some message");
    }
    // parse here the values
    return "result successful result";
}

现在,为了在处理特定异常时返回自定义代码,您可以创建一个完整的单独控制器来执行此操作(尽管您可以在同一控制器中进行操作),该控制器从ResponseEntityExceptionHandler扩展并进行了注释与@RestControllerAdvice一起使用,并且必须具有一种处理该特定异常的方法,如下所示:

异常处理控制器

@RestControllerAdvice
public class ExceptionHandlerController extends ResponseEntityExceptionHandler {

    @ExceptionHandler(MyException.class)
    protected ResponseEntity<Object> handleMyException(MyException ex, WebRequest req) {
        Object resBody = "some message";
        return handleExceptionInternal(ex, resBody, new HttpHeaders(), HttpStatus.NOT_FOUND, req);
    }

}

答案 3 :(得分:1)

您可以执行以下操作:

@PostMapping(value = "/v1/notification")
public ResponseEntity<String> handleNotifications(
 @RequestParam("notification") String itemid) {
   // parse here the values
   return new ResponseEntity<>("result successful result", 
   HttpStatus.OK);
}