如何使用 DefaultHttpClient 写入 OutputStream?

2022-09-03 16:37:15

我如何获得使用?OutputStreamorg.apache.http.impl.client.DefaultHttpClient

我想将一个长字符串写入输出流。

使用时,您将实现它,如下所示:HttpURLConnection

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

有没有一种使用与我上面类似的方法?我该如何写到一个 using 而不是 ?DefaultHttpClientOutputStreamDefaultHttpClientHttpURLConnection

例如

DefaultHttpClient client = new DefaultHttpClient();

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

答案 1

我知道另一个答案已经被接受,只是为了记录,这就是如何使用HttpClient写出内容而无需在内存中进行中间缓冲。

    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);

答案 2

您无法直接从 BasicHttpClient 获取 OutputStream。您必须创建一个对象,并为其提供封装要发送的内容的对象。例如,如果输出足够小以容纳内存,则可以执行以下操作:HttpUriRequestHttpEntity

// 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);

如果数据足够大,需要对其进行流式处理,则会变得更加困难,因为没有接受 OutputStream 的实现。您需要写入临时文件并使用或可能设置管道并使用HttpEntityFileEntityInputStreamEntity

编辑请参阅oleg的答案,以获取演示如何流式传输内容的示例代码 - 毕竟您不需要临时文件或管道。


推荐