gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 15:29:07 24 4
gpt4 key购买 nike

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

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

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

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

现在我想为此接口(interface)编写一些自动化测试。我需要做的方法是使用相同的接口(interface)编写 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
}

希望这有帮助!

关于java - 如何使用为服务器定义的相同接口(interface)编写 Restful 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9776836/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com