Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get http response header in VBScript

Why this .vbs script retrieve null value?

Option Explicit
On Error Resume Next
Dim h: Set h = CreateObject("MSXML2.XMLHTTP")
h.Open "HEAD", "http://google.com/", False
h.send
Dim GetLocation: Set GetLocation = h.getResponseHeader("Location")
MsgBox GetLocation
like image 427
Ali Dbg Avatar asked Oct 30 '25 19:10

Ali Dbg


1 Answers

Almost all HTTP libraries follow redirects by default.
Therefore you can not get Location header as long as you follow the redirects, so you need to stop following redirects.
I recommend two different solutions.

#1 Achieving the final url would be the easiest way instead of getting Location header.

Option Explicit

Dim GetLocation
Const SXH_OPTION_URL = -1

Dim h
Set h = CreateObject("MSXML2.ServerXMLHTTP")
    h.Open "HEAD", "http://google.com/", False 
    h.send
GetLocation = h.getOption(SXH_OPTION_URL) 'final URL even if redirected

MsgBox GetLocation

#2 If you want to make sure you get the first Location header (not the last link in the chain of redirects), you should use WinHttpRequest by disabling redirects, so you can get the header if available.

Option Explicit

Dim GetLocation
Const WHR_EnableRedirects = 6

Dim h
Set h = CreateObject("WinHttp.WinHttpRequest.5.1")
    h.Option(WHR_EnableRedirects) = False 'disable redirects
    h.Open "HEAD", "http://google.com/", False
    h.Send
GetLocation = h.GetResponseHeader("Location") 'an error occurs if not exist

MsgBox GetLocation
like image 153
Kul-Tigin Avatar answered Nov 03 '25 02:11

Kul-Tigin