I do use MultipartEntity to send File to server, it appears correctly in $_FILES
superglobal
But I need also fill in POST body to be read via php://stdin
How can I do that?
current snippet below:
ByteArrayOutputStream bos = new ByteArrayOutputStream(); // stream to hold image
bm.compress(CompressFormat.JPEG, 75, bos); //compress image
byte[] data = bos.toByteArray();
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("REMOTE ADDRESS");
ByteArrayBody bab = new ByteArrayBody(data, "image.jpg");
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE); // is this one causing trouble?
reqEntity.addPart("image", bab); // added image to request
// tried this with no luck
// reqEntity.addPart("", new StringBody("RAW DATA HERE"));
postRequest.setEntity(reqEntity); // set the multipart entity to http post request
HttpResponse response = httpClient.execute(postRequest);
MultipartEntity is part of HttpMime 4.1.2 API, documentation
Similar to this: Android: Uploading a file to a page along with other POST strings
Just add a a few
FormBodyPart
to yourMultipartEntity
.You can use the
StringBody
object to provide the value.Here is an example of how you can use it:
Here is the output of the PHP script:
This doesn't compress all the post vars inside of one content body part but it dose the job.
You can't access the data from php://stdin or $HTTP_RAW_POST_DATA, both are unavailable for multipart/form-data encoding. From the PHP docs:
Even if you set
always_populate_raw_post_data
to On it still won't fix the problem:My best guess is just add all the data as a
ByteArrayBody
orStringBody
and just use that as if you were reading from php://stdinHere is an example of
ByteArrayBody
:And in PHP:
You should get:
Edit: After some second thoughts I think it's better to just use one
StringBody
and put all the data in one post variable, then parse it from that, it skips writing the data to a file and deleting it after the request since the temp file is totally useless this will increase performance. Here is an example:Then from PHP: