使用JSON字符串的请求主体发布帖子的Jax-RS客户端

时间:2011-02-04 23:03:34

标签: scala post jax-rs

我正在使用JaxRS创建与供应商的API交互的客户端代码。我已经能够编写执行GET和POST的代码,这两个代码都没有请求体。我目前遇到一个问题,尝试进行POST,只有一个请求正在发送。我正在尝试发送一个简单的JSON字符串:

{"server":{"name":"HelloKitty","imageId":71,"flavorId":1}}

以下是我正在使用的WebClient的定义(用Scala编写,但我知道标题和授权正在正确完成):

def postClient: WebClient = {
   val authClient = WebClient.create(authServer)
   authClient.header("X-Auth-User", apiUsername)
   authClient.header("X-Auth-Key", apiKey)

   val response = authClient.get
   val metadata = response getMetadata () map { case (k, v) => k -> v(0).toString }

   val client = WebClient.create(metadata.get("X-Server-Management-Url").getOrElse("Error in authentication response"))
   client.header("X-Auth-User", apiUsername)
   client.header("X-Auth-Key", apiKey)
   client.header("X-Auth-Token", metadata.get("X-Auth-Token").getOrElse("Error in authentication response"))
   client.header("Content-Type","application/json")
}

这是我的资源界面:

@Produces(Array("text/json"))
trait RackspaceServerApi {
    @Path("/servers.json")
    @GET
    def listServers(): String

    @Path("/servers/detail.json")
    @GET
    def listServersDetailed(): String

    @POST
    @Path("/servers")
    @Consumes(Array("application/json"))
    def createServerData(server: String)
}

这是我创建代理并尝试发送请求的方法

def createServer(name: String, imageId: Long, flavorId: Int) = {
    // this creates a simple pojo for the server
    val serverObject = new RackspaceCreateServerObject(name, imageId, flavorId, None, None)

    // i am using lift-web to handle the json
    // here I am unmarshalling the serverObject into a json string
    val jsonServerData = write(serverObject)

    val postProxy = JAXRSClientFactory.fromClient(RackspaceConnection.postClient, classOf[RackspaceServerApi], true)
    postProxy.createServerData(jsonServerData)
}

这是我得到的特定WebApplicationException:

状态代码:[500]
实体:[没有为响应类找到消息正文编写器:JAXBElement。]

但是,如果我尝试使用webclient而不是像这样的代理发送请求:

def createServer(name: String, imageId: Long, flavorId: Int) = {
    // this creates a simple pojo for the server
    val serverObject = new RackspaceCreateServerObject(name, imageId, flavorId, None, None)

    // i am using lift-web to handle the json
    // here I am unmarshalling the serverObject into a json string
    val jsonServerData = write(serverObject)

    val webClient = RackspaceConnection.postClient
    webClient.path("/servers")
    webClient.post(jsonServerData)
}

有效。我在界面上做错了什么(缺少一些神奇的注释组合?)?或者我没有设置一些东西? 我使用的是Jax-RS 2.3.2。

1 个答案:

答案 0 :(得分:0)

您使用的是哪种JAX-RS实现?

错误消息表明您需要注册一个插件/模块来处理JAXB bean到JSON的编组。一些JAX-RS实现会自动执行此操作,有些需要初始化。