Tuesday, November 25, 2008

VBScript. How to send a POST or GET to a website.

VBScript. How to send a POST or GET to a website.

Anyone know how to send a POST or GET to a website using VBScript, such as logging in to the website using the script or sending data to a google search. The point is to send a POST or GET or something similar, Thanks everyone!

I'm jumping in a little late here, but I think it's important to note that if the use of XMLHTTP is an acceptable solution, then it is by far the easiest way to accomplish POST and GET actions. Source code is below. I think you'll agree that 3-5 lines of code per actions is pretty slick.

Function httpGET(url)
Set http = Server.CreateObject("Msxml2.ServerXMLHTTP")
http.Open "GET", url, False
httpGET = http.responseText
End Function

' For the "body" parameter, you can pass in the Request.Form object. or use this format to indicate the name of each form element "username=Danny&language=Chinese"
' Example: httpPOST( "http://test.com/", Request.Form, "someone", "password"
Function httpPOST( url, body, username, password )
Set http = Server.CreateObject("Msxml2.ServerXMLHTTP")
http.Open "POST", url, False, username, password
http.setRequestHeader _
"Content-Type", _
http.send body ' example: "username=Danny&language=Chinese"
httpPOST = http.responseText
End Function

About the only hassle comes from special encoding of strings. The function below will do the trick. I didn't write the original upon which this is based, but can't find any info about who did.

Function URLEncode(strInput)
' Convert all "special" characters to %NN style encoding.
' For example, a chr(32) space character is %20
Dim sTemp
Dim sChar
sTemp = ""
sChar = ""

Dim n
Dim ascii
For n = 1 To Len(strInput)
ascii = Asc(Mid(strInput, n, 1))

If ascii >= 65 And ascii <= 90 Then ' A..Z
sTemp = sTemp & Chr(ascii)

ElseIf (ascii >= 97) And (ascii <= 122) Then ' a..z
sTemp = sTemp & Chr(ascii)

ElseIf (ascii >= 48) And (ascii <= 57) Then ' 0..9
sTemp = sTemp & Chr(ascii)

sChar = Trim(Hex(ascii))
If ascii <= 15 Then
sTemp = sTemp & "%0" & sChar
sTemp = sTemp & "%" & sChar
End If
End If
URLEncode = sTemp
End Function

No comments: