vbNewbie
vbNewbie

Reputation: 3345

XML escaped characters

I am trying to send a POST request to add some content to an API box. The rules are that the body format should be XML(values must be XML-escaped), HTTP Method (post), requires authentication(yes), request content(content-type: "application/xml"

<entries?
  <entry tag="some_tag">
   <value>XML-escaped-entry belongs here</value>
  </entry>
  <entry tag="some_tag">
   <value>XML-escaped-entry belongs here</value>
....
...

 </entries>

I send the request as follows and get a 400 bad request error. It worked when I entered one value for entry.

 For i As Integer = 0 To searchItems.Count - (1000 - max)
                data = data + "<entries><entry><value>" & searchItems.Item(i) & "</value></entry></entries>" & vbNewLine
            Next
            If uri.Scheme = uri.UriSchemeHttps Then
                Dim request As HttpWebRequest = HttpWebRequest.Create(uri)
                request.Method = method__1
                request.ContentLength = data.Length
                request.ContentType = "application/xml"
                request.Credentials = New System.Net.NetworkCredential("[email protected]", "xxxxxx")
                Dim writer As New StreamWriter(request.GetRequestStream)
                writer.Write(data)
                writer.Close()
                Dim oResponse As HttpWebResponse = request.GetResponse()
                Dim reader As New StreamReader(oResponse.GetResponseStream())
                Dim tmp As String = reader.ReadToEnd()
                oResponse.Close()
            End If

additional rules: -Best practice is to incrementally add and remove changes to your entry list instead of deleting/recreating the entire list each time a change is necessary. -New entries are placed at the top of the queue for polling and are processed in a LIFO manner.

Upvotes: 2

Views: 5681

Answers (2)

Max Toro
Max Toro

Reputation: 28608

  1. Don't use the + operator to concatenate strings, use StringBuilder.
  2. Don't use StringBuilder to build XML, use XmlWriter, it takes care of your encoding problem.

Upvotes: 3

Schenz
Schenz

Reputation: 1113

You need to Look for and encode special characters during your loop. Something along the lines of:

 For i As Integer = 0 To searchItems.Count - (1000 - max)
            data = data + "<entries><entry><value>" & encodeEntry(searchItems.Item(i)) & "</value></entry></entries>" & vbNewLine
 Next

 Private Function encodeEntry(ByVal entry As String) As String
     Dim returnValue As String = entry

     ' Replace the special characters
     returnValue = returnValue.Replace("&", "&amp;")
     returnValue = returnValue.Replace("""", "&quot;")
     returnValue = returnValue.Replace("'", "&apos;")
     returnValue = returnValue.Replace("<", "&lt;")
     returnValue = returnValue.Replace(">", "&gt;")

     ' return the escaped string
     return returnValue
 End Function

Upvotes: 5

Related Questions