如何使用DefaultHttpClient写入OutputStream? [英] How do I write to an OutputStream using DefaultHttpClient?
问题描述
如何使用 org.apache.http.impl.client.DefaultHttpClient
获取 OutputStream
?
我想在输出流中写一个长字符串。
I'm looking to write a long string to an output stream.
使用 HttpURLConnection
你会像这样实现它:
Using HttpURLConnection
you would implement it like so:
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
OutputStream out = connection.getOutputStream();
Writer wout = new OutputStreamWriter(out);
writeXml(wout);
是否有使用 DefaultHttpClient
的方法类似于我上面有什么?如何使用 DefaultHttpClient
而不是 HttpURLConnection
OutputStream >?
Is there a method using DefaultHttpClient
similar to what I have above? How would I write to an OutputStream
using DefaultHttpClient
instead of HttpURLConnection
?
例如
DefaultHttpClient client = new DefaultHttpClient();
OutputStream outstream = (get OutputStream somehow)
Writer wout = new OutputStreamWriter(out);
推荐答案
您无法直接从BasicHttpClient获取OutputStream。您必须创建一个 HttpUriRequest
对象,并为其提供一个 HttpEntity
,它封装了您要发送的内容。例如,如果您的输出足够小以适合内存,则可以执行以下操作:
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);
如果数据足够大,你需要流式传输,那就更难了,因为没有 HttpEntity
接受OutputStream的实现。您需要写入临时文件并使用 FileEntity
或者可能设置管道并使用 InputStreamEntity
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
编辑请参阅oleg的答案,了解演示如何流式传输内容的示例代码 - 毕竟您不需要临时文件或管道。
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.
这篇关于如何使用DefaultHttpClient写入OutputStream?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!