【问题标题】:Moving from HttpWebRequest to HttpClient从 HttpWebRequest 转移到 HttpClient
【发布时间】:2022-12-30 15:44:54
【问题描述】:

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

【问题讨论】:

  • 有一个关于 HttpClient 的doc。你可能会在那里找到答案

标签: c# .net httpwebrequest dotnet-httpclient


【解决方案1】:
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

【讨论】:

    【解决方案2】:

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

    //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。 阅读更多关于为什么我们不应该像这样实例化HttpClienthere

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多