1

I'm using Groovy's RESTClient/HTTPBuilder library to send GET and POST requests to a webservice. One resource requires a PDF with content type application/pdf. The response will be an XML.

Request --> POST application/pdf
Response <-- application/xml

I have tried the following:

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,
)

Both variants produce:

No encoder found for request content type application/pdf

As far as I have understood the library doesn't support application/pdf by default.

How can I implement the above?

Update from 2015-10-15 after answer by @opal

The following code snippet at least puts the PDF into the request body. However I cannot see the Content-type: application/pdf in the POST request. Also the server rejects the request with "Invalid mime type".

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)
}
Robert Strauch
  • 12,055
  • 24
  • 120
  • 192

1 Answers1

1

What you need to do is to define a custom encoder. Follow the (incomplete) example below:

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)
}

Please try the example above and let me know if it worked.

Opal
  • 81,889
  • 28
  • 189
  • 210
  • Unfortunately it doesn't work. Maybe I got something wrong? Here's my code: [link](http://pastebin.com/6qERsNtJ) Exception: `No signature of method: encodePDF() is applicable for argument types: (org.apache.http.entity.FileEntity)` – Robert Strauch Oct 14 '15 at 21:12
  • Pass a File itself, not FileEntity. – Opal Oct 14 '15 at 21:28
  • Sorry, maybe it's too late in the evening :) Would you mind adding that to your code above? – Robert Strauch Oct 14 '15 at 21:34
  • It seems as if I can't see the wood for the trees. [Here is my code](http://pastebin.com/6qERsNtJ) and I can't find any major differences to yours. However I get the exception. – Robert Strauch Oct 15 '15 at 07:26
  • 1
    Instead of `body: encodePDF(new File('C:/temp/test.pdf')),` it should be: `body: new File('C:/temp/test.pdf'),` – Opal Oct 15 '15 at 07:27
  • Needed to add the `headers` map to the request: `response = client.post( uri: url, headers: [ 'Content-Type': 'application/pdf' ], body: new File('C:/temp/test.pdf'), requestContentType: 'application/pdf' )` – Robert Strauch Oct 15 '15 at 20:49