该问题可以使用Fiddler进行分析,它比livehttp标头提供更多的细节。使用Fiddler composer功能,您可以尝试POST请求并查看响应。
我对提供的URL感到满意,并且发现由于未在请求中设置JSESSIONID cookie,响应会返回一个消息“您的会话已过期”。
张贴的要求:
POST http://www.mca.gov.in/DCAPortalWeb/dca/CompanyMaster.do HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host: www.mca.gov.in
Content-Length: 64
taskID=9412&method=find&cmpnyname=&cmpnyID=U24232TN2004PLC054527
的回应:
HTTP/1.1 200 OK
Date: Thu, 08 Jan 2015 11:31:55 GMT
Server: IBM_HTTP_Server
Surrogate-Control: no-store
Expires: Thu, 01 Dec 1994 16:00:00 GMT
Cache-Control: no-cache="set-cookie, set-cookie2"
X-UA-Compatible: IE=edge
Vary: Accept-Encoding
Content-Type: text/html;charset=ISO-8859-1
Content-Language: en-US
via: HTTP/1.1 proxy226
Proxy-Connection: Keep-Alive
Connection: Keep-Alive
Set-Cookie: JSESSIONID=0000NHNQgGMo247hf4dpRRcsrLP:17ufavb50; Path=/
Content-Length: 702
在响应主体,我们有消息 “您的会话已过期”。
如果您第一次进入主页,将设置一个cookie,并将其传递给进一步的调用。当你直接提出POST请求时,JSESSIONID cookie没有设置。
您需要首先在您的VBA代码中打开主页,然后阅读响应标头以识别cookie,然后使用它填充POST请求标头。还要注意,POST必须在不带?method = getName的URL“http://www.mca.gov.in/DCAPortalWeb/dca/CompanyMaster.do”上完成。还需要使用responsebody来创建填充excel文件的数据。
示例代码:
Sub test_new()
Dim result As String
Dim myURL As String, postData As String
Dim Cookie As String
Dim winHttpReq As Object
Dim oStream As Object
Dim objStream As Object
Set winHttpReq = CreateObject("MSXML2.XMLHTTP")
' GET the JSESSIONID cookie first frm home page
myURL = "http://www.mca.gov.in/DCAPortalWeb/dca/MyMCALogin.do?method=setDefaultProperty&mode=31"
winHttpReq.Open "GET", myURL, False
winHttpReq.send
' Get the JSESSIONID from cookies ''' JSESSIONID=0000QSz0qJtUmQ8QRmEGBbVBFsm:18ungce99; Path=/
Cookie = Split(winHttpReq.getResponseHeader("Set-Cookie"), ";")(0)
myURL = "http://www.mca.gov.in/DCAPortalWeb/dca/CompanyMaster.do" ' ?method=getName"
postData = "taskID=9412&method=find&cmpnyname=&cmpnyID=U24232TN2004PLC054527"
winHttpReq.Open "POST", myURL, False
winHttpReq.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
' POST the request with cookies
winHttpReq.setRequestHeader "Cookie", Cookie
winHttpReq.send (postData)
' Get Text from response Body
If winHttpReq.Status = 200 Then
Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1
oStream.Write winHttpReq.responseBody
oStream.Position = 0
oStream.Type = 2 'Text
oStream.Charset = "UTF-8"
result = oStream.ReadText
End If
Sheets("Sheet1").Range("A1") = result
End Sub
注意这仅保存的HTML代码到单元格A1。如果您确实想使用html内容,则应使用htmlfile对象或将流保存到本地文件中,并使用oStream.SaveToFile
,并使用它代替oStream.Position = 0
中的代码。