.net 从HttpWebRequest移动到HttpClient

dced5bon  于 2023-01-03  发布在  .NET
关注(0)|答案(2)|浏览(148)

我想将一些遗留代码从使用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并获得响应?

iyfamqjs

iyfamqjs1#

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

mkshixfv

mkshixfv2#

您不需要访问请求流,您可以直接发送有效负载,但如果背后有原因,也可以这样做。

//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。

相关问题