Uploading txt file via POST request with HttpBuilder

六月ゝ 毕业季﹏ 提交于 2019-12-11 18:18:24

问题


I want to upload a txt file to a website using a POST request with HTTPBuilder and multipart/form-data

I've tried running my function and I get a HTTP 200 OK response, but the file doesn't appear on the website anywhere.

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
}

From debugging this is the status recieved

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]"

Anything I'm doing wrong? I don't get any errors but it just seems like nothing happens.


回答1:


I don't have anything conclusive, but I suspect there is something invalid with the way you set up the multipart upload.

To help figure this out, below is a standalone, working, multipart upload groovy script using HttpBuilder:

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

The script assumes a file data.txt with the data to post in the current directory. The script posts to httpbin.org as a working test endpoint, adjust accordingly to post to your endpoint instead.

Saving the above in test.groovy and executing will yield something like:

~> 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] 

(note that first run will take a while as groovy grapes need to download the http-builder dependency tree)

perhaps starting with this working example and working your way back to your code would help you pinpoint whatever is not working in your code.



来源:https://stackoverflow.com/questions/54123972/uploading-txt-file-via-post-request-with-httpbuilder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!