通过HttpBuilder通过POST请求上传txt文件

时间:2019-01-10 07:43:32

标签: post groovy httprequest multipartform-data

我想使用带有HTTPBuilder和multipart / form-data的POST请求将txt文件上传到网站

我尝试运行函数,并收到HTTP 200 OK响应,但是该文件未出现在网站上的任何地方。

private Map fileUpload(String url, File file){
    log.debug "doPost: $url body: ${file.getName()}"
    FileBody fileBody = new FileBody(file,ContentType.APPLICATION_OCTET_STREAM)
    def result = [:]
    try {
        def authSite = new HTTPBuilder(url)
        authSite.auth.basic(user, password)
        authSite.request(POST) { req ->
            headers.Accept = "application/json, text/javascript, */*; q=0.01"
            req.params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 20000)
            req.params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000)
            def mpe = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE)
            mpe.addPart("gxt",fileBody)
            req.setEntity(mpe)
            response.success = { resp, reader ->
                result = reader
            }
            response.failure = { resp, reader ->
                println "My response handler got response: ${resp.statusLine}"
            }
        }
    }
    catch (e) {
        log.debug("Could not perform POST request on URL $url", e)
        throw e
    }
    return result
}

通过调试,这是收到的状态

3695 [main] DEBUG org.apache.http.wire  -  << "HTTP/1.1 200 OK[\r][\n]"
3695 [main] DEBUG org.apache.http.wire  -  << "Date: Thu, 10 Jan 2019 07:34:06 GMT[\r][\n]"

我做错了什么吗?我没有任何错误,但似乎什么也没发生。

1 个答案:

答案 0 :(得分:0)

我没有任何决定性的内容,但我怀疑您设置分段上传的方式存在某些问题。

为帮助弄清这一点,下面是一个使用HttpBuilder的独立的,可工作的,多部分的上载groovy脚本:

@Grab('org.codehaus.groovy.modules.http-builder:http-builder:0.7.1')
@Grab('org.apache.httpcomponents:httpmime:4.2.1')

import org.apache.http.entity.mime.content.* 
import org.apache.http.entity.mime.*
import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.Method.POST

fileUpload('https://httpbin.org/post', new File('data.txt'))

Map fileUpload(String url, File file){
  println "doPost: $url body: ${file.name}"
  def result 
  try {
    new HTTPBuilder(url).request(POST) { req ->
      requestContentType = "multipart/form-data"

      def content = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE)
      content.addPart(file.name, new InputStreamBody(file.newInputStream(), file.name))
      req.entity = content

      // json might be something else (like a reader) 
      // depending on the response content type
      response.success = { resp, json -> 
        result = json
        println "RESP: ${resp.statusLine}, RESULT: $json"
      }

      response.failure = { resp, json ->
        println "My response handler got response: ${resp.statusLine}"
      }
    }
  } catch (e) {
    println "Could not perform POST request on URL $url"
    throw e
  }

  result
}

脚本假定文件data.txt包含要发布到当前目录中的数据。该脚本作为工作测试端点发布到httpbin.org,请相应地进行调整以发布到您的端点。

将以上内容保存在test.groovy中并执行将产生类似以下内容:

~> groovy test.groovy
doPost: https://httpbin.org/post body: data.txt
RESP: HTTP/1.1 200 OK, RESULT: [args:[:], data:, files:[data.txt:{ "foo": "bar" }], form:[:], headers:[Accept:*/*, Connection:close, Content-Type:multipart/form-data; boundary=ZVZuV5HAdPOt2Sv7ZjxuUHjd8sDAzCz9VkTqpJYP, Host:httpbin.org, Transfer-Encoding:chunked], json:null, origin:80.252.172.140, url:https://httpbin.org/post] 

(请注意,第一次运行将花费一些时间,因为时髦的葡萄需要下载http-builder依赖关系树)

也许从这个工作示例开始,然后逐步回到代码中,这将帮助您查明代码中不起作用的地方。