2010-12-17 79 views
11

我剛剛開始使用REST,我一直在閱讀this帖子和提及的book關於REST response codes。當我在玩的Controller類看起來不過,它似乎被限制在返回在Play中返回RESTful響應代碼

  • 200 - OK
  • 301 - 永久
  • 302動了 - 發現
  • 304 - 未修改
  • 400 - 不良要求
  • 401 - 未經授權
  • 403 - 禁止使用
  • 404 - 未找到
  • 5XX

這似乎離開了被提及的是一些可能有用的代碼:

  • 201 - 創建(成功JSON後反響不錯?)
  • 202 - 接受(對於排隊請求)
  • 204 - 無內容(成功PUT/POST/DELETE的可能響應)
  • 307 - 臨時重定向
  • 405 - 不允許的方法
  • 406 - 不接受
  • 409 - 衝突
  • 410 - 飄
  • 415 - 不支持的媒體類型(這似乎是對JSON格式的請求相應的響應時,沒有JSON模板被定義)是指那些不畢竟需要

? Play是否自動處理這些情況?

此外,由於網頁總是以200的形式返回,所以似乎一個控制器無法處理相同資源的REST請求和正常網頁請求。我錯過了什麼嗎?

回答

11

綜觀播放的源代碼(播放1.1)在play.mvc.Http.StatusCode對象,播放似乎有以下代碼

public static final int OK = 200; 
public static final int CREATED = 201; 
public static final int ACCEPTED = 202; 
public static final int PARTIAL_INFO = 203; 
public static final int NO_RESPONSE = 204; 
public static final int MOVED = 301; 
public static final int FOUND = 302; 
public static final int METHOD = 303; 
public static final int NOT_MODIFIED = 304; 
public static final int BAD_REQUEST = 400; 
public static final int UNAUTHORIZED = 401; 
public static final int PAYMENT_REQUIERED = 402; 
public static final int FORBIDDEN = 403; 
public static final int NOT_FOUND = 404; 
public static final int INTERNAL_ERROR = 500; 
public static final int NOT_IMPLEMENTED = 501; 
public static final int OVERLOADED = 502; 
public static final int GATEWAY_TIMEOUT = 503; 

這將表明您的部分已經確定了碼的確認時,如201中,然而,值307,405,406,409,410和415不在那裏。

另外,201,202,204被確認,但不被引用的其他地方的源代碼內。所以,除非Netty的服務器,或提供的jar文件中的一個管理這些用於播放(這我不知道它可以做),我看不出玩就怎麼能神奇地處理這些情況不知道代碼庫。

查看renderJSON的代碼,它不會將狀態碼設置爲發回結果的一部分(因此使用默認值200),因此以下hack 可能會工作。

public static void myJsonAction() { 
    response.status = 201; 
    renderJSON(jsonString); // replace with your JSON String 
} 
+0

我測試了設置'response.status'果然,它就是這麼簡單。 – 2010-12-23 02:34:58

+0

這個常量在Play 2.x中有什麼想法? Play 2.x Scala如何? – 2015-07-02 03:32:07

+0

找到Scala 2.x響應代碼play.api.mvc.Results#NoContent – 2015-07-02 05:21:03

4

在當前的Play版本中,您必須改用status()。例如:

status(201, jsonData); 

在Scala中它應該工作在這個例子中從official docs採取:

Status(488)("Strange response type") 
+0

我該如何在scala中使用它,我在那裏搜索的方法不像status() – 2015-12-24 10:10:25

相關問題