Wednesday, December 23, 2009

HTTP GET and POST methods in VBScript

We can get the http response of a website with VBScript using XMLHTTP methods. In this post I am including a sample code using which one can use the GET and POST methods on some sample sites.

  Option Explicit

  Dim FSO, objTextFile, Path, strWebSite

  On Error Resume Next
  'The Website URL
  strWebSite = "http://automationexpertsforum.blogspot.com/"

  'Getting the current directory Path into a variable
  Path = Replace(Wscript.ScriptFullName, Wscript.ScriptName, "")

  'Calling the HTTP Get and Writing the response into text file
  Set FSO = CreateObject("Scripting.FileSystemObject")    'Creating File System Object for writing the code into the text file
  Set objTextFile = FSO.OpenTextFile(Path & "HTTPGetResponse.txt", 8, True)    'Open the text file
  objTextFile.WriteLine Hget(strWebSite)    'Writing the response into the text file
  objTextFile.Close    'Close the Text File

  'Calling the HTTP Post and Writing the response into text file
  Set objTextFile = FSO.OpenTextFile(Path & "HTTPPostResponse.txt", 8, True)    'Open the text file
  objTextFile.WriteLine Hpost("http://www.xchangebooks.net/home?destination=node%2F1", "name="&strUsername&"&pass="&strPassword&"&op=Log+in&form_build_id=form-dedc377ad8922e3fa40dc6a80674002c&form_id=user_login_block")    'Writing the response into the text file
  objTextFile.Close    'Close the Text File
  Set FSO = Nothing    'Release the File System Object

Function Hget(strURL)
  Dim objHTTP
  Set objHTTP = CreateObject("Microsoft.XMLHTTP")    'Create XML HTTP object for the Get method
  objHTTP.Open "GET", strURL, False    'Opening the HTTP get method
  objHTTP.Send()    'Sending the request
  If Err.Number = 0 And objHTTP.Status = 200 Then    'objHTTP.Status returns the status code of the HTTP Get Request
    Hget = objHTTP.ResponseText    'ResponseText returns the response HTML code in text format
  Else
    Hget = "HTTP Error returned! Error Code = " & objHTTP.Status
  End If
  Set objHTTP = Nothing
End Function    '==> HTTP GET Method

Function Hpost(strURL, strDatatoSend)
  Dim objHTTP
  Set objHTTP = CreateObject("Microsoft.XMLHTTP")    'Create XML HTTP object for the Post method
  objHTTP.open "POST", strURL, False    'Opening the HTTP post method
  objHTTP.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
  objHTTP.send strDatatoSend    'Sending the request
  If Err.Number = 0 And objHTTP.Status = 200 Then    'objHTTP.Status returns the status code of the HTTP Post Request
    Hpost = objHTTP.ResponseText    'ResponseText returns the response HTML code in text format
  Else
    Hpost = "HTTP Error returned! Error Code = " & objHTTP.Status
  End If
  Set objHTTP = Nothing
End Function    '==> HTTP POST method

1 comment: