2011-09-04 61 views
5

我正在Scala中使用Lift网络框架实现REST服务,并且我在PUT请求中遇到了一些问题以创建一个我知道该ID的新实体。电梯REST服务无法识别PUT请求

已加入派遣Boot.scala和我的休息服务对象看起来有点像这样:

$ curl http://localhost:8080/api/room/abs 
{ 
    "id":"abs" 
} 

现在我想:我与测试

package code 
package lib 

import model._ 

import net.liftweb._ 
import common._ 
import http._ 
import rest._ 
import util._ 
import Helpers._ 
import json._ 

object RestService extends RestHelper { 

    serve("api"/"room" prefix { 
    // /api/room returns all the rooms 
    case Nil JsonGet _ => Room.registredRooms: JValue 
    // /api/room/count gets the room count 
    case "count" :: Nil JsonGet _ => JInt(Room.registredRooms.length) 
    // /api/room/room_id gets the specified room (or a 404) 
    case Room(room) :: Nil JsonGet _ => room: JValue 
    // DELETE the room in question 
    case Room(room) :: Nil JsonDelete _ => 
     Room.delete(room.id).map(a => a: JValue) 
    // PUT adds the room if the JSON is parsable 
    case Nil JsonPut Room(room) -> _ => Room.add(room): JValue 

    // POST if we find the room, merge the fields from the 
    // the POST body and update the room 
    case Room(room) :: Nil JsonPost json -> _ => 
     Room(mergeJson(room, json)).map(Room.add(_): JValue) 
    }) 

} 

GET请求是否工作正常实施创建服务,我不断得到一个404没有找到当我PUT:

$ curl -i -H "Accept: application/json" -X PUT -d "[{'id':'abs'}]" http://localhost:8080/api/room/ 
HTTP/1.1 404 Not Found 
Expires: Sun, 4 Sep 2011 14:13:50 UTC 
Set-Cookie: JSESSIONID=t1miz05pd5k9;Path=/ 
Content-Length: 106 
Cache-Control: no-cache, private, no-store 
Content-Type: text/html; charset=utf-8 
Pragma: no-cache 
Date: Sun, 4 Sep 2011 14:13:50 UTC 
X-Lift-Version: 2.4-M3 
Server: Jetty(6.1.22) 

<!DOCTYPE html> 
<html> <body>The Requested URL /api/room/ was not found on this server</body> </html> 

在SBT我可以看到,该请求被确认为PUT请求:

15:13:50.130 [[email protected] - /api/room/] INFO net.liftweb.util.TimeHelpers - Service request (PUT) /api/room/ returned 404, took 10 Milliseconds 

什么可能是错的任何想法?

回答

5

您测试PUT请求的方式有三个问题。

最重要的是,您需要将Content-Type标头设置为application/json(而不是或除Accept标头之外)。

接下来,您需要在JSON中使用双引号:-d '[{"id":"abs"}]'。 (双引号实际上是required for strings in valid JSON。一些JSON解析器将接受单引号,但不是Lift的。)

最后,从URL中删除尾部斜杠。它将"index"添加到路径列表的末尾,这意味着您的case Nil JsonPut...行中不会匹配。

下面应该工作:

curl -i -H "Content-Type: application/json" -X PUT -d '[{"id":"abs"}]' http://localhost:8080/api/room 
+0

它的确!非常感谢特拉维斯:) –

+0

有什么办法可以不要求'Content-Type'? –

+0

有用的答案,但我不得不说,当客户端错误发送格式错误的JSON(例如,正确地发送“Content-键入:application/json'标题,但在主体中发送'foo')。我得到它可能是一个模式匹配问题或其他什么,但它会使调试更直接,如果它返回400错误请求或什么。 –