1

I need to Post the XML data to a URL.But I am facing some Error in the (Stream requestStream = request.GetRequestStream()) Line Errror Image . I have saved the xml in the file and provided the path for that . I think there is Issue while passing XML Data but when I try to use the same XML in the POSTMan using POSTmethod.I can able to get the response Data.

This is the reference link HTTP post XML data in C#

And here is my code

static void Main(string[] args)
    {
    

        string url = "*****************";
        XmlDocument Xdoc = new XmlDocument();
        Xdoc.Load(@"Path of the xml file");
        var sw = new StringWriter();
        Xdoc.Save(sw);
        string result = sw.ToString();
        string response = **********.postXMLData(url, result);
        Console.WriteLine(response);
        Console.ReadLine();
    }

public static string postXMLData(string destinationUrl, String requestXml)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl);
        byte[] bytes;
        bytes = System.Text.Encoding.ASCII.GetBytes(requestXml);
        request.ContentType = "text/xml; encoding=utf-8";
        request.ContentLength = bytes.Length;
        request.Method = "POST";
        using (Stream requestStream = request.GetRequestStream())
        {
            requestStream.Write(bytes, 0, bytes.Length);
        }
        HttpWebResponse response;
        response = (HttpWebResponse)request.GetResponse();
        if (response.StatusCode == HttpStatusCode.OK)
        {
            Stream responseStream = response.GetResponseStream();
            string responseStr = new StreamReader(responseStream).ReadToEnd();
            return responseStr;
        }
        return null;
    }
Noob Gamer
  • 11
  • 1
  • Usually this means one of the HTTP headers are wrong. The default headers in c# are different from Postman. Normally this means that in c# you have to add the missing header. But this can also occur if HTTPS is failing (secure mode using TLS). What version of Net are you using? Best thing to do is to use Net 4.7.2 or later which uses operating System for TLS. Earlier versions of Net performed TLS and the encryption modes in Net were not always working. Then if you are using a phone the operating system/kernel may need upgrading. – jdweng Jun 30 '22 at 10:47

0 Answers0