[英]Moving from HttpWebRequest to HttpClient
我想將一些遺留代碼從使用 HttpWebRequest 更新為使用 HttpClient,但我不太確定如何將字符串發送到我正在訪問的 REST API。
遺留代碼:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "text/xml";
request.ContentLength = payload.Length;
if (credentials != null)
{
request.Credentials = credentials;
}
// Send the request
Stream requestStream = request.GetRequestStream();
requestStream.Write(payload, 0, payload.Length);
requestStream.Close();
// Get the response
response = (HttpWebResponse)request.GetResponse();
我可以像處理 web 請求那樣使用 HttpClient.GetStreamAsync 方法並使用 stream 嗎? 或者有沒有辦法對內容使用 SendAsync 然后得到響應?
你不需要訪問請求stream,你可以直接發送payload,但如果背后有原因,那么這也是可以的。
//Do not instantiate httpclient like that, use dependency injection instead
var httpClient = new HttpClient();
var httpRequest = new HttpRequestMessage();
//Set the request method (e.g. GET, POST, DELETE ..etc.)
httpRequest.Method = HttpMethod.Post;
//Set the headers of the request
httpRequest.Headers.Add("Content-Type", "text/xml");
//A memory stream which is a temporary buffer that holds the payload of the request
using (var memoryStream = new MemoryStream())
{
//Write to the memory stream
memoryStream.Write(payload, 0, payload.Length);
//A stream content that represent the actual request stream
using (var stream = new StreamContent(memoryStream))
{
httpRequest.Content = stream;
//Send the request
var response = await httpClient.SendAsync(httpRequest);
//Ensure we got success response from the server
response.EnsureSuccessStatusCode();
//you can access the response like that
//response.Content
}
}
關於憑據,你需要知道這些是什么憑據? 是基本授權嗎?
如果它是基本身份驗證,那么您可以(在HttpRequestMessage
object 中設置請求 URI 時,您也可以在那里構建憑據。
var requestUri = new UriBuilder(yourEndPoint)
{
UserName = UsernameInCredentials,
Password = PasswordInCredentials,
}
.Uri;
然后您只需將其設置為請求 URI。 在此處閱讀有關為什么我們不應該像這樣實例化HttpClient
的更多信息
using var handler = new HttpClientHandler { Credentials = ... };
using var client = new HttpClient(handler);
var content = new StringContent(payload, Encoding.UTF8, "text/xml");
var response = await client.PostAsync(uri, content);
我假設payload
是一個string
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.