2015-10-13 21 views
1

我正在使用Groovy的RESTClient/HTTPBuilder庫將GET和POST請求發送到web服務。一種資源需要內容類型爲application/pdf的PDF。響應將是一個XML。在Groovy中設置內容類型「application/pdf」RESTClient/HTTPBuilder

請求 - > POST應用/ PDF
響應< - 應用程序/ XML

我曾嘗試以下:

def client = new RESTClient(url) 
client.post(
    uri: url, 
    body: new File('C:/temp/test.pdf').bytes, 
    requestContentType: 'application/pdf' 
) 

def client = new RESTClient(url) 
client.setContentType('application/pdf') 
client.post(
    uri: url, 
    body: new File('C:/temp/test.pdf').bytes, 
) 

兩個變體產生:

無編碼找到請求內容類型的應用程序/ pdf

據我瞭解,該庫默認不支持application/pdf

我該如何執行上述操作?至少從答案後2015年10月15日

更新由@opal

下面的代碼片段放PDF到請求主體。但是我在POST請求中看不到Content-type: application/pdf。此外,服務器拒絕具有「無效MIME類型」的請求。

client.encoder.putAt('application/pdf', new MethodClosure(this, 'encodePDF')) 
response = client.post(
    uri: url, 
    body: new File('C:/temp/test.pdf'), 
    requestContentType: 'application/pdf' 
) 

HttpEntity encodePDF(File pdf) { 
    new FileEntity(pdf) 
} 

回答

1

你需要做的是定義一個自定義編碼器。按照下面的(不完整)示例:

import org.codehaus.groovy.runtime.MethodClosure 
import org.apache.http.entity.FileEntity 

//this part adds a special encoder  
def client = new RESTClient('some host') 
client.encoder.putAt('application/pdf', new MethodClosure(this, 'encodePDF')) 

//here is the method for the encoder added above 
HttpEntity encodePDF(File pdf) { 
    new FileEntity(pdf) 
} 

請嘗試上面的示例,並告訴我它是否工作。

+0

不幸的是它不起作用。也許我錯了?這裏是我的代碼:[鏈接](http://pastebin.com/6qERsNtJ)例外:'沒有方法簽名:encodePDF()適用於參數類型:(org.apache.http.entity.FileEntity)' –

+0

通過a文件本身,而不是FileEntity。 – Opal

+0

對不起,也許晚上太晚了:)你介意在你的代碼上面添加那個嗎? –