【发布时间】: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之类的东西吗?