I was told to migrate a post request written in HttpWebRequest to HttpRequestMessage. I've provided the old code and the new code that I've developed below.
- In the old code they are sending the byte stream over to the endpoint. I'm not sure whether using HttpWebRequest demands data to be sent as bytes or not.
- In the new code, I've created a StringContent to be sent to the endpoint. Are both the codes equivalent and works the intended way?
If not, some help to modify the new code is appreciated.
Using HttpWebRequest (old code)
//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();
Using HttpRequestMessage (new code)
//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)