【问题标题】:A Jax-RS client that does a post with a request body of a JSON string使用 JSON 字符串的请求正文进行发布的 Jax-RS 客户端
【发布时间】:2011-06-21 16:28:21
【问题描述】:

我正在使用 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。]

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

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。

【问题讨论】:

  • 您知道您的RackspaceConnection 示例发送的是什么Content-Type 标头吗?可以使用multipart/form-data 之类的东西吗?

标签: scala post jax-rs


【解决方案1】:

您使用的是什么 JAX-RS 实现?

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

【讨论】:

    猜你喜欢
    • 2018-09-11
    • 2013-08-07
    • 2014-07-11
    • 2015-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-25
    相关资源
    最近更新 更多