具有自定义请求的HttpClient.GetStreamAsync()? [英] HttpClient.GetStreamAsync() with custom request?
问题描述
我的目标是使用HttpClient
类进行Web请求,以便我可以将响应写入文件(解析后).因此,我需要将结果作为Stream
.
My goal is to use the HttpClient
class to make a web-request so that I can write the response to a file (after parsing). Therefore I need the result as a Stream
.
HttpClient.GetStreamAsync()仅将字符串requestUri
作为参数.因此,无法使用自定义HttpRequestHeader
,自定义HttpMethod
,自定义 ContentType ,自定义内容等来创建请求吗?
HttpClient.GetStreamAsync() only takes the string requestUri
as parameter. So there is no possibility to create a request with custom HttpRequestHeader
, custom HttpMethod
, custom ContentType, custom content and so on?
我看到HttpWebRequest
有时 Headers
.那么我可以使用HttpClient
,应该使用HttpWebRequest
还是完全使用其他类/库?
I saw that HttpWebRequest
is sometimes used instead, but in my PCL (Profile111) there is no Add
method for the Headers
. So can I use HttpClient
, should I use HttpWebRequest
instead or should I use another class/library at all?
推荐答案
GetStreamAsync
只是构建和发送无内容的GET请求的快捷方式.做到漫长的路要走".非常简单:
GetStreamAsync
is just a shortcut for building and sending a content-less GET request. Doing it the "long way" is fairly straightforward:
var request = new HttpRequestMessage(HttpMethod.???, uri);
// add Content, Headers, etc to request
request.Content = new StringContent(yourJsonString, System.Text.Encoding.UTF8, "application/json");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
response.EnsureSuccessStatusCode();
var stream = await response.Content.ReadAsStreamAsync();
这篇关于具有自定义请求的HttpClient.GetStreamAsync()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!