繁体   English   中英

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

[英]How to write a Restful client using the same Interface defined for the server

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

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

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

该服务运行良好,我使用Web浏览器对其进行了测试。

现在,我想为此界面编写一些自动化测试。 我需要做的方法是使用相同的接口编写一个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 不允许编写,而是执行编写。 您要做的就是创建自己的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
}

希望这可以帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM