htm11h
htm11h

Reputation: 1779

passing a utf8 encoded string to web service

Can I pass a UTF8 encoded string to a web service?

UPDATED:

Function EncodeToUTF(ByVal toEncode As String) As String
    Dim utf8 As New UTF8Encoding()

    Dim encodedBytes As Byte() = utf8.GetBytes(toEncode)
    Dim returnValue As String = utf8.GetString(encodedBytes)
    returnValue = HttpUtility.UrlEncode(returnValue)
    Return returnValue
End Function 

And then decode this on the web server? The issue is that the XML Web Service parser is striping out CRs from my string.

Then on server side to decode:

Function DecodeFromUTF8(ByVal encodedData As String) As String
    Dim utf8 As New UTF8Encoding()

    Dim returnValue As String = HttpUtility.UrlDecode(encodedData)
    Dim encodedDataAsBytes As Byte() = utf8.GetBytes(returnValue)

    returnValue = utf8.GetString(encodedDataAsBytes)

    Return returnValue
End Function

The returnValue here is still encoded.

Upvotes: 1

Views: 1163

Answers (1)

Learner
Learner

Reputation: 4004

You need to URL encode your string/message. Messages must be URL Encoded before being sent to a webservice as they contain special characters.

Function EncodeToUTF(ByVal toEncode As String) As String
    Dim utf8 As New UTF8Encoding()

    Dim encodedBytes As Byte() = utf8.GetBytes(toEncode)
    Dim returnValue As String = utf8.GetString(encodedBytes)

    '' URL encode your string before pushing it to a web service
    returnValue = HttpUtility.UrlEncode(returnValue)

    Return returnValue
End Function

And, on the other server side, use the following to decode your encoded string:

Dim decodedUrl As String = HttpUtility.UrlDecode(encodedUrl)

Hopefully, this will solve your issue.

Upvotes: 1

Related Questions