簡體   English   中英

返回創建方法的結果和201狀態碼

[英]Return result of create method and 201 status code

如何在rest api和201狀態碼中返回create方法的結果? 在此代碼中,狀態代碼為200,如何將其更改為201?

    Path("/student")    
    public class MyRestApi{

    @Path("/create")
    public Response create(){
           Student student = new Student;
           //insert in data source
           Return Response.ok(student).build();
          }
}

您可以使用ResponseBuilder.status(int)Response.status(int)方法並將其發送為:-

Response.ok(student).status(201).build(); // 201 is the response code

要么

Response.status(201).ok(student).build(); // 201 is the response code

我建議將ResponseBuilder與可讀的Status枚舉一起使用:

import javax.ws.rs.core.Response.Status;
[...]
return Response.status(Status.CREATED).entity("created the student" 
    + "- this is your customized message to the caller").build();

有點晚了,但是如果其他任何人都應該偶然發現這個問題…… 這里提供的使用創建的方法答案似乎更合適,因為它使用了設計用於在創建資源時返回響應的方法,並且既不對響應代碼進行硬編碼,也不需要其他代碼調用以設置Location標頭。

該答案的摘錄:

響應API

公共靜態Response.ResponseBuilder created(URI location) -為創建的資源創建一個新的ResponseBuilder,使用提供的值設置位置標頭。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM