如何使用为服务器定义的相同接口编写Restful客户端

时间:2012-03-19 19:47:25

标签: java scala resteasy

我正在使用Scala编写Restful服务。

在服务器端,它有一个接口:

trait ICustomerService {
  @GET
  @Path("/{id}")
  @Produces(Array("application/xml"))
  def getCustomer(@PathParam("id") id: Int): StreamingOutput
}

该服务运行正常,我使用网络浏览器对其进行了测试。

现在我想为这个界面编写一些自动化测试。我需要做的是使用相同的接口编写RESTEasy客户端:

class CustomerServiceProxy(url : String) {
  RegisterBuiltin.register(ResteasyProviderFactory.getInstance());
  val proxy = ProxyFactory.create(classOf[ICustomerService], url)

  def getCustomer(id: Int): Customer = {
    val streamingOutput = proxy.getCustomer(id)
    <Problem here>
  }
}

此代码不起作用,因为流输出仅允许写入。

如何编写此测试类,以便我可以从客户端获取服务器写入streamingoutput的内容?

非常感谢

1 个答案:

答案 0 :(得分:1)

StreamingOutput不允许写入,执行写入。您所要做的就是创建自己的OutputStream来捕获它:

/**
 * Re-buffers data from a JAXRS StreamingOutput into a new InputStream
 */
def rebuffer(so: StreamingOutput): InputStream = {
  val os = new ByteArrayOutputStream
  so.write(os)
  new ByteArrayInputStream(os.toByteArray())
}


def getCustomer(id: Int): Customer = {
  val streamingOutput = proxy.getCustomer(id)
  val inputStream = rebuffer(streamingOutput)
  inputStream.read() // or pass it to an XML parser or whatever
}

希望这有帮助!