LoginSignup
2
2

More than 5 years have passed since last update.

GroovyのHttpBuilderでファイルアップロード

Last updated at Posted at 2014-03-13

HttpClient経由だと日本語ファイル名が化けてしまうのはまだ未解決。

@Grab('org.codehaus.groovy.modules.http-builder:http-builder:0.7')
import groovyx.net.http.HTTPBuilder
import groovyx.net.http.ContentType
import static groovyx.net.http.ContentType.TEXT
import static groovyx.net.http.Method.POST

@Grab('org.apache.httpcomponents:httpmime:4.3.2')
import org.apache.http.entity.mime.MultipartEntityBuilder
import org.apache.http.util.EntityUtils
import static org.apache.http.entity.ContentType.TEXT_PLAIN

def URL_ROOT = 'http://...'
def http = new HTTPBuilder(URL_ROOT)

http.request( POST, TEXT ) { req ->
    uri.path = '/path/to/upload'
    req.entity = MultipartEntityBuilder
        .create()
        .setCharset(Charset.forName('UTF-8')) // Java7 以降なら StandardCharsets.UTF_8
        .addTextBody('hoge', 'ほげほげ', TEXT_PLAIN.withCharset('UTF-8'))
        .addBinaryBody('importFile', file) // java.io.File
        .build()

    response.success = { res, reader ->
        def responseBytes = EntityUtils.toByteArray(res.getEntity())
        def bis = new ByteArrayInputStream(responseBytes)
        // ... 用途に合わせてレスポンス処理
    }

    response.failure = { res, reader ->
        // 失敗時
    }
}

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2