简体   繁体   English

从 HttpWebRequest 转移到 HttpClient

[英]Moving from HttpWebRequest to HttpClient

I would like to update some legacy code from using HttpWebRequest to use HttpClient, but I am not quite sure how to send string to the REST API I am accessing.我想将一些遗留代码从使用 HttpWebRequest 更新为使用 HttpClient,但我不太确定如何将字符串发送到我正在访问的 REST API。

Legacy code:遗留代码:

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

Can I use the HttpClient.GetStreamAsync method and use the stream like we did with the web request?我可以像处理 web 请求那样使用 HttpClient.GetStreamAsync 方法并使用 stream 吗? Or is there a way to use SendAsync with content and then get the response?或者有没有办法对内容使用 SendAsync 然后得到响应?

You do not need to access the request stream, you could just directly send the payload, but if there is a reason behind that then this is also possible.你不需要访问请求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
    }
}

About the credentials, you need to know what kind of credentials are these?关于凭据,你需要知道这些是什么凭据? Is it basic auth?是基本授权吗?

If it's basic auth then you could (while setting the request URI in the HttpRequestMessage object, you could construct the credentials there as well.如果它是基本身份验证,那么您可以(在HttpRequestMessage object 中设置请求 URI 时,您也可以在那里构建凭据。

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

And then you just set that as request URI.然后您只需将其设置为请求 URI。 Read more about why we shouldn't instantiate HttpClient like this here 在此处阅读有关为什么我们不应该像这样实例化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);

I've assumed that payload is a string .我假设payload是一个string

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM