从 HttpWebRequest 转移到 HttpClient

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

我可以使用 HttpClient.GetStreamAsync 方法并像处理 Web 请求那样使用流吗?或者有没有办法对内容使用 SendAsync 然后获得响应?

你不需要访问请求流,你可以直接发送负载,但如果背后有原因,那么这也是可能的。

//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 对象中设置请求 URI 时,您也可以在那里构建凭据。

var requestUri = new UriBuilder(yourEndPoint)
                        {
                            UserName = UsernameInCredentials,
                            Password = PasswordInCredentials,
                        }
                        .Uri;

然后您只需将其设置为请求 URI。 详细了解为什么我们不应该像这样实例化 HttpClient here

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

我假设 payloadstring