【问题标题】:Setting content type "application/pdf" in Groovy RESTClient / HTTPBuilder在 Groovy RESTClient / HTTPBuilder 中设置内容类型“application/pdf”
【发布时间】:2016-01-11 17:46:34
【问题描述】:

我正在使用 Groovy 的 RESTClient/HTTPBuilder 库向 Web 服务发送 GET 和 POST 请求。一个资源需要内容类型为application/pdf 的PDF。响应将是一个 XML。

请求 --> POST 申请/pdf
响应

我尝试了以下方法:

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

两种变体都产生:

未找到请求内容类型 application/pdf 的编码器

据我了解,该库默认不支持application/pdf

我怎样才能实现上述?

@opal 回答后于 2015 年 10 月 15 日更新

以下代码 sn -p 至少将 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)
}

【问题讨论】:

    标签: rest groovy content-type httpbuilder


    【解决方案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)
    }
    

    请尝试上面的示例并告诉我它是否有效。

    【讨论】:

    • 不幸的是它不起作用。也许我做错了什么?这是我的代码:link 异常:No signature of method: encodePDF() is applicable for argument types: (org.apache.http.entity.FileEntity)
    • 传递文件本身,而不是 FileEntity。
    • 抱歉,晚上可能太晚了 :) 你介意将它添加到上面的代码中吗?
    • 好像只见树木不见森林。 Here is my code 我找不到与您的任何重大差异。但是我得到了例外。
    • 应该是 body: encodePDF(new File('C:/temp/test.pdf')), 而不是:body: new File('C:/temp/test.pdf'),
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-06
    • 2015-11-10
    • 2015-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-28
    相关资源
    最近更新 更多