0

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)
1
  • Your first code sample doesn't set req.Method, which is GET by default. Doesn't do any encryption of data either (while second one does). Commented Dec 12, 2022 at 17:06

1 Answer 1

1
+50

I suppose it depends on what the intent was originally :-)

HttpWebRequest is very flexible to what it will send out. Byte[], FormUrlEncodedContent, Multipart Content, Stream, String, ...you get the idea.

There are some performance considerations, again depending on your content. End of the day if you test it and it passes within the required parameters, then you should be OK. Given someone is telling you to do it, it might be in your best interest to ask said someone a few additional questions.

One thing that does stick out to me, in the original code your string is encoded in UTF8 and your new code appears to perhaps be something else. May want to explicitly call out the encoding parameter of StringContent if you choose to keep going that way.

Here's a quick example that should get you up and going. A little inflated, but hopefully it helps you out :-)

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

                    }
                }
            }
        }
    });  
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.