Migrating from ASPTear to MSXML2.ServerXMLHTTP

So I had to migrate some classic ASP code that uses ASPTear to instead use MSXML2.ServerXMLHTTP. ASPTear was used to get some HTML newsletters and email them. The problem was that there were strange characters returned by MSXML2.ServerXMLHTTP for any character above 127. After some digging online, turns out we have to get the data as binary and not as text and then convert the binary data into a string. I also decided to convert characters above 127 into this representation, &#127, to be sure they will display well in the emails. Hopefully this will help someone out there who's also migrating to MSXML2.ServerXMLHTTP.

ASPTear example code:

Dim objTear, myResponse
Dim myURL, Request_POST, Request_GET, strQueryStringOrPostData, strUsername, strPassword

Set objTear = CreateObject("SOFTWING.ASPtear")
myURL = "http://yourwebsite.com"
Request_POST = 1
Request_GET = 2
strQueryStringOrPostData = "&param=value"
strUsername = "theusername"
strPassword = "thepassword"

myResponse = objTear.Retrieve(myURL, Request_GET, strQueryStringOrPostData, strUsername, strPassword)

MSXML2 example code:
So be aware that responseText in MSXML2.ServerXMLHTTP assumes data is ASCII, so chars above 127 come back as 255. To solve that problem get the data using responseBody and then convert binary to a string. Below is an example:

Dim objTear, myResponse,
Dim myURL

Set objTear = CreateObject("MSXML2.ServerXMLHTTP.6.0")
myURL = "http://yourwebsite.com"
objTear.Open "GET", myURL, False
objTear.send ""

' Convert binary result to string.
myResponse = Stream_BinaryToString(objTear.responseBody, "iso-8859-1")

Sub Save2File (sText, sFile)
Dim oStream
Set oStream = CreateObject("ADODB.Stream")
With oStream
.Open
.CharSet = "iso-8859-1"
.WriteText sText
.SaveToFile sFile, 2
End With
Set oStream = Nothing
End Sub

'Code from http://www.motobit.com/tips/detpg_binarytostring/
'Stream_BinaryToString Function
'2003 Antonin Foller, http://www.motobit.com
'Binary - VT_UI1 | VT_ARRAY data To convert To a string
'CharSet - charset of the source binary data - default is "us-ascii"
Function Stream_BinaryToString(Binary, CharSet)
Const adTypeText = 2
Const adTypeBinary = 1

'Create Stream object
Dim BinaryStream 'As New Stream
Set BinaryStream = CreateObject("ADODB.Stream")

'Specify stream type - we want To save text/string data.
BinaryStream.Type = adTypeBinary

'Open the stream And write text/string data To the object
BinaryStream.Open
BinaryStream.Write Binary

'Change stream type To binary
BinaryStream.Position = 0
BinaryStream.Type = adTypeText

'Specify charset For the source text (unicode) data.
If Len(CharSet) > 0 Then
BinaryStream.CharSet = CharSet
Else
BinaryStream.CharSet = "us-ascii"
End If

'Open the stream And get binary data from the object
Stream_BinaryToString = BinaryStream.ReadText
End Function

Add new comment