How do I write to an OutputStream using DefaultHttpClient?
httpclient, java, outputstream
Solution
You can't get an OutputStream from BasicHttpClient directly. You have to create an `HttpUriRequest` object and give it an `HttpEntity` that encapsulates the content you want to sent. For instance, if your output is small enough to fit in memory, you might do the following:
// Produce the output
ByteArrayOutputStream out = new ByteArrayOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
writeXml(writer);
// Create the request
HttpPost request = new HttpPost(uri);
request.setEntity(new ByteArrayEntity(out.toByteArray()));
// Send the request
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(request);
If the data is large enough that you need to stream it, it becomes more difficult because there's no `HttpEntity` implementation that accepts an OutputStream. You'd need to write to a temp file and use `FileEntity` or possibly set up a pipe and use `InputStreamEntity`
EDIT See oleg's answer for sample code that demonstrates how to stream the content - you don't need a temp file or pipe after all.
Problem
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); ```