2012-03-19 14 views
0

我正在使用Scala編寫Restful服務。如何使用爲服務器定義的接口編寫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> 
    } 
} 

此代碼將無法正常工作流輸出只允許寫。

如何編寫此測試類,以便我可以獲取服務器從客戶端寫入流輸出的內容?

非常感謝

回答

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 
} 

希望這有助於!

相關問題