简体   繁体   中英

How i can send file in body of the post request? groovy

I have a file as a byte array. I want to send it in the body of a post request.

I have an example in JavaScript that works great. Can't repeat the same code in groovy. The server returns "Initial Server Error". I'm sure the problem is in the type of data being passed.

Groovy code:

def reqParams = [:];
reqParams.filename = 'test.pdf'
reqParams.filedata = utils.readFileContent(obj.clientFile) // array of byte
reqParams.destination = 'test'

def jsonBody = new JsonBuilder(reqParams).toString()

// build HTTP POST

def client = new RESTClient(baseUrl)
client.auth.basic 'user1', 'user1'
def resp = client.post(body : jsonBody, contentType: JSON)

Example body of request generating with help JS:

Content-Type: multipart/form-data; boundary=--------------------------295349461296500421390407
Content-Length: 659
----------------------------295349461296500421390407
Content-Disposition: form-data; name="filedata"; filename="query.txt"

<query.txt>
----------------------------295349461296500421390407
Content-Disposition: form-data; name="destination"

workspace://SpacesStore/716afb88-715a-4413-85bc-f71630abfd51
----------------------------295349461296500421390407
Content-Disposition: form-data; name="filename"

jasperTextToNextStrin.txt

----------------------------295349461296500421390407--

How I can send POST request with Groovy?

The JSON format doesn't natively support binary data. To send binary data in a JSON payload you would need to encode it as text somehow.

What encoding you should use depends on what the server expects.

A common encoding would be base 64 encoding :

reqParams.filedata = myFile.bytes.encodeBase64().toString()

or

reqParams.filedata = utils.readFileContent(obj.clientFile).encodeBase64().toString()

if readFileContent indeed returns a byte[] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM