none
Post XML using webclient RRS feed

  • Question

  • I have a situation whereby I need to post some xml data at a target web page.  Here is my code:


    Dim objRequest As HttpWebRequest = WebRequest.Create("http://mywebserver/page.asp")

    objRequest.ContentLength = sXML.Length
    objRequest.ContentType = "application/x-www-form-urlencoded"
    objRequest.Method = "POST"

    Dim stmWriter = New System.IO.StreamWriter(objRequest.GetRequestStream())
    stmWriter.Write(sXML)
    stmWriter.Close()

    Dim objResponse As System.Net.HttpWebResponse = objRequest.GetResponse()
    Dim stmReader = New System.IO.StreamReader(objResponse.GetResponseStream())
    Dim stringResult = stmReader.ReadToEnd()
    stmReader.Close()
    'The string sXML contains my xml data.

     



    If I run this code, I receive the error:
    System.Net.WebException: The remote server returned an error: (500) Internal Server Error.
       at System.Net.HttpWebRequest.CheckFinalStatus()
       at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
       at System.Net.HttpWebRequest.GetResponse()


    Thinking slightly logically (which is unusual for me!!) I thought that it might be a config problem with the server, or a problem with the xml.  So I built the follwoing html page, to test both items at once:

    <HTML>
    <BODY>
       <Form Action="http://mywebserver/page.asp" method="post">
          <textarea name="myField"></textarea>
          <input type="submit">
       </Form>
    </BODY>
    </HTML>

    I pasted the xml (contained within sXML) into the myField text box, and clicked on submit.  Although I half expected a http 500 error, it actually successfully returned what it should have done (which is a success message generated by the asp).

    So what I'm wondering, is why would the server return a 500 message when doing the post through my code?  (or in other words, whats wrong with my code?!)

    Thursday, June 16, 2005 11:11 AM

Answers

  • You forgot to encode form data prior to send on server:


            ...
             ' add reference to System.Web
            Dim formData As String = "myField=" & System.Web.HttpUtility.UrlEncode(sXML) 
            objRequest.ContentLength = formData.Length
            ...
            stmWriter.Write(formData)
            ...

     


    .. or rewrite ASP page to read xml stream instead of form field
    Thursday, June 16, 2005 1:37 PM

All replies

  • You forgot to encode form data prior to send on server:


            ...
             ' add reference to System.Web
            Dim formData As String = "myField=" & System.Web.HttpUtility.UrlEncode(sXML) 
            objRequest.ContentLength = formData.Length
            ...
            stmWriter.Write(formData)
            ...

     


    .. or rewrite ASP page to read xml stream instead of form field
    Thursday, June 16, 2005 1:37 PM
  • Dude, you da man...

    Works, sweet as a nut!
    Thursday, June 16, 2005 4:57 PM