Reputation: 23
I have an image byte array which I need to send to a servlet on a server using HTTP client. We know how to send normal text data but unable to send the image data.
We created a string data from image byte array using the following code:
String imageData = new String(imagebyteArr);
And sent the above String
to servlet through HTTP client, but when we again retrieve byte array from string using below code:
imageByteArr = imageData.toByteArray();
The resultant byte array is modified one, where in -127 is replaced on 63.
How to solve this unexpected behavior?
Upvotes: 0
Views: 586
Reputation: 89169
I would totally discourage you with taking image byte array and converting to String
as you will have to worry about character encoding.
One thing to do is send the byte array directly using ByteArrayEntity
, as follows:
HttpPost post = new HttpPost(url);
post.setEntity(new ByteArrayEntity(bytes));
post.setHeader("Content-type", ""application/octet-stream");
Don't forget to set your Content-Type
to the correct image appropriately.
Upvotes: 1
Reputation: 24630
Strings get encoded. You have 2 posibilities: encode binary data as base64 (for example) send the base64 and decode on server side or binary upload with a PUT request.
Upvotes: 2