Kjensen
Kjensen

Reputation: 12374

Bad Request when posting xml to REST-like service - specal characters

I am integrating an app with a service (iContact), that describes its API as "rest-like". I post XML, and everything works fine... Until I send special characters like æøå - then I get a "bad request" error from the server.

<contacts>
  <contact>
    <firstname>Søren</firstname>
    <lastname>ÆbleTårn</lastname>
  </contact>
</contact>

I tried putting firstname and lastname values in cdata, but that did not help.

Is there some encoding I can apply to values (similar to html-encode), or do I need to move in another direction?

I doubt the problem is specific to .Net, but the answer might be, so here is the code I use:

Dim xml as string = GenerateXml()
Dim http As New HttpClient("http://uri.to/rest")
Dim resp As HttpResponseMessage = http.Post(String.Empty, HttpContent.Create(xml))

Upvotes: 0

Views: 1410

Answers (3)

Kjensen
Kjensen

Reputation: 12374

After being pointed in the right direction by the answers, I wrote this function to xmlencode the text.

Public Function XmlEncode(ByVal text As String) As String
    For i As Integer = 127 To 255
        text = Replace(text, Chr(i), "&#" & i.ToString & ";")
    Next
    return text
End Function

I am sure it could be more effective, but performance is not really an issue, as this will run infrequently.

Upvotes: 0

Jeff Leonard
Jeff Leonard

Reputation: 3294

It seems likely that this web service isn't using the same character set encoding as your application. Typical encodings are UTF-8 or UTF-16. Look in the service documentation (or if that fails look in the service response) for the character encoding and see if there is an encoding specified. If one is specified, verify that it matches the encoding used in your client's request.

It is also good practice to XMLEncode the data.

Upvotes: 1

Ned Batchelder
Ned Batchelder

Reputation: 375564

You can use numeric entities in XML to help with some encoding issues:

<firstname>S&#xf8;ren</firstname>

But you still have to be sure the server is coded correct to receive, process and store these characters. It's hard to know where the error is here...

Upvotes: 1

Related Questions