How do I write to an OutputStream using DefaultHttpClient?

Fabii picture Fabii · Apr 13, 2012 · Viewed 25.4k times · Source

How do I get an OutputStream using org.apache.http.impl.client.DefaultHttpClient?

I'm looking to write a long string to an output stream.

Using HttpURLConnection you would implement it like so:

HttpURLConnection connection = (HttpURLConnection)url.openConnection();
OutputStream out = connection.getOutputStream();
Writer wout = new OutputStreamWriter(out);
writeXml(wout);

Is there a method using DefaultHttpClient similar to what I have above? How would I write to an OutputStream using DefaultHttpClient instead of HttpURLConnection?

e.g

DefaultHttpClient client = new DefaultHttpClient();

OutputStream outstream = (get OutputStream somehow)
Writer wout = new OutputStreamWriter(out);

Answer

ok2c picture ok2c · Apr 14, 2012

I know that another answer has already been accepted, just for the record this is how one can write content out with HttpClient without intermediate buffering in memory.

    AbstractHttpEntity entity = new AbstractHttpEntity() {

        public boolean isRepeatable() {
            return false;
        }

        public long getContentLength() {
            return -1;
        }

        public boolean isStreaming() {
            return false;
        }

        public InputStream getContent() throws IOException {
            // Should be implemented as well but is irrelevant for this case
            throw new UnsupportedOperationException();
        }

        public void writeTo(final OutputStream outstream) throws IOException {
            Writer writer = new OutputStreamWriter(outstream, "UTF-8");
            writeXml(writer);
            writer.flush();
        }

    };
    HttpPost request = new HttpPost(uri);
    request.setEntity(entity);