Since Android developers removed Apache HTTP Client, I am moving to HttpURLConnection. I was able to rewrite all my functions except one. I am sending byte array (image) with name and date. Actually my function allow sending many images at once, but I am sending only one. Until now, I was using MultipartEntityBuilder to build HttpEntity and set it by httpPost.setEntity(entity). However I want to get rid of MultipartEntityBuilder.
Right now I have following code snippet:
public void sendImage(URL url, byte[] image, String name, long date) {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entityBuilder.addBinaryBody("file[]", image);
entityBuilder.addTextBody("file_name[]", name);
entityBuilder.addTextBody("file_size[]", String.valueOf(date));
HttpEntity entity = entityBuilder.build();
conn.addRequestProperty(entity.getContentType().getName(), entity.getContentType().getValue());
OutputStream os = conn.getOutputStream();
entity.writeTo(os);
os.close();
conn.connect();
// read response code
}
At server side I can receive data like this:
$file = $_POST['file'];
$file_name = $_POST['file_name'];
$file_size = $_POST['file_size'];
I can not change server implementation.
I tried solution from this thread: Sending files using POST with HttpURLConnection But I do not know how to adjust it to my server.
Is there a way to get rid of HttpEntity? I do not want to use other library (Volley, OkHttp or Retrofit) right now. I will probably move to one of them in future.
Thanks for help.