Robert Strauch
Robert Strauch

Reputation: 12896

Setting content type "application/pdf" in Groovy RESTClient / HTTPBuilder

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

Upvotes: 1

Views: 2583

Answers (1)

Opal
Opal

Reputation: 84844

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.

Upvotes: 1

Related Questions