繁体   English   中英

C# 为 HttpWebRequest 代码创建等效的 HttpRequestMessage

[英]C# Creating Equivalent HttpRequestMessage for HttpWebRequest code

有人告诉我将用HttpWebRequest编写的发布请求迁移到HttpRequestMessage 我在下面提供了旧代码和我开发的新代码。

  • 在旧代码中,他们将字节流发送到端点。 我不确定使用HttpWebRequest是否要求数据以字节形式发送。
  • 在新代码中,我创建了一个要发送到端点的StringContent 这两个代码是否等效并且按预期方式工作?

如果没有,一些帮助修改新代码表示赞赏。

使用HttpWebRequest (旧代码)

//postData -> data to be sent(type string)

HttpWebRequest req = (HttpWebRequest)WebRequest.Create("someurl.net");
req.ContentType = "application/xml";
req.Accept = "application/xml";

byte[] postBytes = Encoding.UTF8.GetBytes(postData);

req.ContentLength = postBytes.Length;
    
Stream postStream = req.GetRequestStream();
    
postStream.Write(postBytes, 0, postBytes.Length);
    
postStream.Flush();
postStream.Close();
    
WebResponse resp = req.GetResponse();

使用HttpRequestMessage (新代码)

//postData -> data to be sent(type string)

var request = new HttpRequestMessage(HttpMethod.Post, $"{address}");
request.Headers.Add("Accept", "application/xml");
request.Headers.Add("Content-Type", "application/xml");

request.Content = new StringContent(RSAEncryptDecrypt.EncryptResponse(postData));
await _client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken)

我想这取决于最初的意图:-)

HttpWebRequest对于发送的内容非常灵活。 Byte[], FormUrlEncodedContent, Multipart Content, Stream, String ……你明白了。

有一些性能考虑因素,同样取决于您的内容。 一天结束时,如果您对其进行测试并在要求的参数范围内通过,那么您应该没问题。 既然有人告诉你这样做,那么问别人一些额外的问题可能最符合你的利益。

有一件事确实让我印象深刻,在原始代码中,您的字符串是用UTF8编码的,而您的新代码似乎可能是别的东西。 如果您选择继续这样做,可能需要显式调出StringContent的编码参数。

这是一个简单的示例,可以帮助您入门。 有点膨胀,但希望它能帮助你:-)

public static void PostSomeContent(string data_parameter, string uri_parameter){
    HttpRequestMessage _httpRequestMessage;
    MemoryStream _memoryStream;
    StreamWriter _streamWriter;
    StreamContent _streamContent;
    HttpClient _client;
    HttpResponseMessage _httpResponse;

    //Initilize a HttpRequest Message
    _httpRequestMessage = 
        new HttpRequestMessage();

    //Set the end point
    //You could also do this in the intilization
    _httpRequestMessage.RequestUri = 
        new Uri(uri_parameter);

    //Set your headers
    _httpRequestMessage.Headers.Add("Accept", "application/xml");
    _httpRequestMessage.Headers.Add("Content-Type", "application/xml");

    //Set the methood
    _httpRequestMessage.Method = 
        HttpMethod.Post;

    //I'm asuming you want it to be async
    Task.Run(async()=>{

        //Set up the stream
        using(_memoryStream = new MemoryStream()){
            using(_streamWriter = new StreamWriter(_memoryStream)){

                _streamWriter.Write(data_parameter);
                _streamWriter.Flush();
                _memoryStream.Seek(
                    offset:0,
                    loc: System.IO.SeekOrigin.Begin
                );

                using(_streamContent = new StreamContent(_memoryStream)){
                    
                    _httpRequestMessage.Content = _streamContent;
                    
                    _client = 
                       new HttpClient();

                    try{

                        //Use the client to send your message
                        //Configure what you want back via completion option
                        using(_httpResponse = await _client.SendAsync(
                            request: _httpRequestMessage,
                            completionOption: HttpCompletionOption.ResponseHeadersRead)){

                                //Or however you would like to make sure there was no error
                                _httpResponse.EnsureSuccessStatusCode();

                                //If you want the response as a string:
                                string _content = await _httpResponse.Content.ReadAsStringAsync();

                                //Or response in a stream:
                                using(Stream _responseStream = await _httpResponse.Content.ReadAsStreamAsync()){

                                }
                        }
                    }
                    catch(Exception){

                        //Handle your exception

                    }
                }
            }
        }
    });  
}

暂无
暂无

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

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