【问题标题】:Can't send InputStream object using grails rest-client-builder无法使用 grails rest-client-builder 发送 InputStream 对象
【发布时间】:2013-09-12 17:29:17
【问题描述】:

我一直在使用 rest-client-builder 插件 (http://grails.org/plugin/rest-client-builder),但在将文件作为 inputStream 对象发送时遇到了问题。

来自插件文档:

通过将请求主体的属性设置为 File、URL、byte[] 或 InputStream 实例,可以实现多部分请求:

def resp = rest.post(url) {
        contentType "multipart/form-data"
        zip = new File(pluginPackage)
        pom = new File(pomFile)
        xml = new File(pluginXmlFile)
    }

我的代码:

def post(String url, InputStream photo, String contentType, Cookie[] cookies = null) {
    def rest = new RestBuilder()

    def cookiesHeaderString = ""
    if (cookies) {
        cookiesHeaderString = WebUtils.buildCookiesHeader(cookies)
    }

    def resp = rest.post(url) {
        header "Cookie", cookiesHeaderString
        file = photo
        contentType "multipart/form-data"
    }

    return resp?.responseEntity?.body
}

有人可以建议我如何发送 InputStream 对象或我做错了什么吗?

【问题讨论】:

  • 你的代码出了什么问题?
  • contentType 出了点问题:消息:空行 |方法->> 307 | javax.activation.MimetypesFileTypeMap 中的 getContentType

标签: rest grails grails-plugin


【解决方案1】:

对于文件类型,我们需要在 RequestCustomizer 上设置“文件”属性。下面的代码对我有用。

File myFile = new File("myFile.txt")

def restResponse = rest.post(url) {
   header headerName, headerValue
   contentType "multipart/form-data" 
   setProperty "file", myFile
}

【讨论】:

    【解决方案2】:

    我知道我得到这个答案已经很晚了,但我一直在寻找答案,但似乎没有任何效果。所以,经过反复试验,我终于找到了我的答案,所以想把它贴在这里。

    RestTemplate restTemplate=new RestTemplate()
        restTemplate.setRequestFactory(new  HttpComponentsClientHttpRequestFactory());
    
     def restBuilder=new RestBuilder(restTemplate)  
    File f = new File("C:/Users/USER/Documents/hello.txt")
     MultiValueMap<String, File> form = new LinkedMultiValueMap<String, File>()
     form.add("fileUpload", f)
             return client.post(path) {
                   auth('ngtest1', 'ngtest1')
                   header :['contentType':"multipart/form-data"]
                   setProperty "fileUpload", f
                   body (form)
             }
    

    这对我有用。我在我的应用程序中将名称命名为“fileUpload”。希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多