-1

I am working on a c# console application where I am making a Http Post request to a web api by using xml file and I'm kind of new to XML and web services but I figured out the following code for the request but failed to pass xml data to the method

static void Main(string[] args)
        {
            string desturl=@"https://xyz.abcgroup.com/abcapi/";
            Program p = new Program();
            System.Console.WriteLine(p.WebRequestPostData(desturl, @"C:\Applications\TestService\FixmlSub.xml"));
        }

        public  string WebRequestPostData(string url, string postData)
        {
            System.Net.WebRequest req = System.Net.WebRequest.Create(url);

            req.ContentType = "text/xml";
            req.Method = "POST";

            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(postData);
            req.ContentLength = bytes.Length;

            using (Stream os = req.GetRequestStream())
            {
                os.Write(bytes, 0, bytes.Length);
            }

            using (System.Net.WebResponse resp = req.GetResponse())
            {
                if (resp == null) return null;

                using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()))
                {
                    return sr.ReadToEnd().Trim();
                }
            }
        }

For obvious reasons the above code throws 404 error as I think I am not passing the xml data properly

May I know how I can fix this?

DoIt
  • 3,270
  • 9
  • 51
  • 103
  • 404 means that the URL could not be found. You need to activate some authentication mechanism to retrieve https:// content from System.Net.WebRequest, see http://stackoverflow.com/questions/560804/how-do-i-use-webrequest-to-access-an-ssl-encrypted-site-using-https for example. – birdypme Jun 25 '15 at 14:54
  • So, am I passing the xml data properly? – DoIt Jun 25 '15 at 14:58

1 Answers1

1

You're not posting xml, your posting the string C:\Applications\TestService\FixmlSub.xml

Change your method call from:

System.Console.WriteLine(p.WebRequestPostData(desturl, @"C:\Applications\TestService\FixmlSub.xml"));

to

var xml = XElement.Load(@"C:\Applications\TestService\FixmlSub.xml");
System.Console.WriteLine(p.WebRequestPostData(desturl, xml.ToString(SaveOptions.DisableFormatting));

If you are trying to learn post / receive, go for it. But there are open source libraries that are already well tested to use if you want to use them.

The non-free version of Servicestack. And their older free-version. I think the older free version is great. I've never tried the newer one. You deal with objects, like say an Employee and pass that to the library and it does the translation to xml or whatever the web-service wants.

You can post whole strings if you want. They have great extension methods to help you with that too.

Chuck Savage
  • 11,775
  • 6
  • 49
  • 69