在不知道其最终大小的情况下发送数据块也很容易使用 Apache 库。这是一个简单的例子:
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
是一个应该包含实体主体的流。您可以dis
使用管道流将输入流与输出流连接起来。因此,一个线程可能正在创建数据(例如,从麦克风录制声音),而另一个线程可能会将其发送到服务器。
// 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
应该传递给动态创建数据的线程,传递给dis
向服务器发送数据的线程。
另见:http ://www.androidadb.com/class/ba/BasicHttpEntity.html