Sending data in chunk not knowing its final size is also quite easy using Apache library. Here is a simple example:
DataInputStream dis;
...
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost:8080");
BasicHttpEntity entity = new BasicHttpEntity();
entity.setChunked(true);
entity.setContentLength(-1);
entity.setContent(dis);
httppost.setEntity(entity);
HttpResponse response = null;
try {
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO
} catch (IOException e) {
// TODO
}
...
// processing http response....
dis
is a stream which should contain entity body. You can pipe dis
input stream with an output stream using piped streams. Therefore, one thread might be creating data (e.g. recording sound from microphone) and the other one might send it to the server.
// creating piped streams
private PipedInputStream pis;
private PipedOutputStream pos;
private DataOutputStream dos;
private DataInputStream dis;
...
pos = new PipedOutputStream();
pis = new PipedInputStream(pos);
dos = new DataOutputStream(pos);
dis = new DataInputStream(pis);
// in thread creating data dynamically
try {
// writing data to dos stream
...
dos.write(b);
...
} catch (IOException e) {
// TODO
}
// Before finishing thread, we have to flush and close dos stream
// then dis stream will know that all data have been written and will finish
// streaming data to server.
try {
dos.flush();
dos.close();
} catch (Exception e) {
// TODO
}
dos
should be passed to thread which creates data dynamically, dis
to the one sending data to the server.
See also: http://www.androidadb.com/class/ba/BasicHttpEntity.html