POST-ing text and files with HTTPBuilder and MultipartEntity
-
07-07-2021 - |
Вопрос
I am using groovyx.net.http.HTTPBuilder to POST from Grails to a PHP script. I need to attach a couple of text fields and a number of files.
I can attach a few textfields this way with great success:
MultipartEntity mpc = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE)
mpc.addPart("json", new StringBody(json.toString()))
But, when I attach a file like this, the textfields are no longer present in the request:
passFiles.each() { key, value ->
mpc.addPart(key, new InputStreamBody(value.stream, value.type, value.filename))
System.out << value
}
I think the file should be okay to add this way. Here is my trace from the above:
[filename:icon.png, stream:java.io.ByteArrayInputStream@2747ebcb, type:image/png]
How can I cause HTTPBuilder to make this Multipart POST as intended?
Решение 2
Andrew's comment caused me to take a better look at the HTTPClient Java API. I was able to make everything work as above like this:
Save a temporary copy of the stream to a file.
def file = new File('web-app/tmpfiles/file.dat').newOutputStream() file << stream file.close()
Instead of using InputStreamBody, use FileBody with the path to the saved file.
mpc.addPart(key, new FileBody(new File('web-app/tmpfiles/file.dat'), filename, type, 'UTF-8'))
Другие советы
A few thoughts:
- Did you remember to call
setEntity()
to link your request with yourMultipartEntity
? - Depending on the version of Grails/Groovy you're using, you may be running into issue(s) in HTTPBuilder, described here. That link points to a patched fork, which I haven't tried.
- It's less than Groovy, but I've been able to accomplish a similar task from Grails with code that sticks closely to the Apache HTTPClient Java API.