kmiklas
kmiklas

Reputation: 13443

How to serialize a byte array to send as the body of an HTTP POST?

How can a Java byte array be properly serialized to send in the body of a POST request?

Is it correct to simply invoke the toString() method?

Specifically, I am compressing a string with gzip, storing in a byte[] array, serializing, and sending to an http POST endpoint. Ty.

EDIT: For posterity, I was using the java.net.http.HttpRequest library, which provides different methods for various body types; for example:

HttpRequest.BodyPublishers.ofByteArray(msg_byte_arr)
HttpRequest.BodyPublishers.ofString(msg_str)

Upvotes: 1

Views: 1612

Answers (1)

rzwitserloot
rzwitserloot

Reputation: 103263

a byte[] array is ready to send straight as a POST request - you should have a .getOutputStream() method, which gets you an output stream (make sure to guard it using try-with-resources). Call its .write() method. Do not use the ObjectOutputStream advised in a comment.

Upvotes: 2

Related Questions