使用 HttpClient,如何将 XDocument 直接保存到请求流?
使用 HttpWebRequest,我可以调用 XDocument.Save() 来直接写入请求流:
XDocument doc = ...;
var request = (HttpWebRequest)WebCreate.Create(uri);
request.method = "POST";
Stream requestStream = request.GetRequestStream();
doc.Save(requestStream);
是否可以使用 HttpClient
执行相同的操作?直接的方法是
XDocument doc = ...;
Stream stream = new MemoryStream();
doc.Save(stream);
var content = new System.Net.Http.StreamContent(stream);
var client = new HttpClient();
client.Post(uri, content);
但这会在 MemoryStream
中创建 XDocument
的另一个副本。
Using HttpWebRequest, I can call XDocument.Save() to write directly to the request stream:
XDocument doc = ...;
var request = (HttpWebRequest)WebCreate.Create(uri);
request.method = "POST";
Stream requestStream = request.GetRequestStream();
doc.Save(requestStream);
Is it possible to do the same thing with HttpClient
? The straight-forward way is
XDocument doc = ...;
Stream stream = new MemoryStream();
doc.Save(stream);
var content = new System.Net.Http.StreamContent(stream);
var client = new HttpClient();
client.Post(uri, content);
But this creates another copy of the XDocument
in the MemoryStream
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
XDocument.Save()
需要一个可写入的Stream
。StreamContent
需要一个可以读取的流。因此,您可以使用两个 Stream,其中一个充当另一个 Stream 的转发器。我认为框架中不存在这种类型,但您可以自己编写一个:不幸的是,您无法从同一线程同时读取和写入这些流。但是您可以使用
Task
从另一个线程写入:XDocument.Save()
expects aStream
that can be written to.StreamContent
expects a stream that can be read. So, you can use a twoStream
s, where one acts as as a forwarder for the other one. I don't think such type exists in the framework, but you can write one yourself:Unfortunately, you can't read and write to those streams at the same time from the same thread. But you can use
Task
to write from another thread: