When i wrote a http get request in vba to get the session id , instead of getting the session id , i am getting an HTML code in the immediate window?
Why is this so?
So basically , when you open the link on browser it will first ask the user to enter his username and password , then it will show him the session id.
But when i select the link in vba code , it shows me the html code
Sub Button1_Click()
Dim objRequest As Object
Dim strUrl As String
Dim blnAsync As Boolean
Dim strResponse As String
Set objRequest = CreateObject("MSXML2.XMLHTTP")
strUrl = "url to be entered"
blnAsync = True
With objRequest
.Open "GET", strUrl, blnAsync
.SetRequestHeader "Content-Type", "application/json"
.Send
'spin wheels whilst waiting for response
While objRequest.readyState <> 4
DoEvents
Wend
strResponse = .ResponseText
End With
Debug.Print strResponse
End Sub
Related
I have this code but i cant seem to get around how to use same code with body parameters. I have to add two body parameters of number = 123456 and first_name = james. Please help update the following code to allow that and work within VB6.
Dim sUrl As String
Dim response As String
Dim xmlhttp
Set sUrl = "http://my.domain.com/service/operation/param"
Set xmlhttp = Server.CreateObject("MSXML2.ServerXMLHTTP")
xmlhttp.open "POST", sURL, False
xmlhttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
xmlhttp.send()
Dim response As String = xmlhttp.responseText
Set xmlhttp = Nothing
I am currently trying to make a msgbox for a userform that I am making that responds with the data from the below javascript using VBA
$.ajax({
type: "GET",
url: app.global.AppPath + 'Dashboard/GetComments',
async: false,
data: {
id: 1015998
},
success: function(result) {}
});
VBA Code:
Private Sub UserForm_Click()
Dim strUrl As String
strUrl = "https://charter.osp-cloud.com/ATOM/Dashboard/GetComments"
Set hReq = CreateObject("MSXML2.XMLHTTP")
With hReq
.Open "GET", strUrl, False
.SetRequestHeader "Content-Type", "text/json"
.Send "id=1015998"
End With
MsgBox hReq.ResponseText
End Sub
Does anyone know what I am doing wrong? Is it because I am not sending a object .Send "{id: 1015998}"?
UPDATE:
upon a little more research I found that maybe parsejson might work but I cant seem to get it to recognize that there is an object
Dim JSON As Dictionary
Set JSON = JsonConverter.ParseJson("{""id"": 1015998}")
Error says "Object Required"
response pulled is below
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult GetComments(Int32)' in 'EZTRACKER.Controllers.DashboardController'.
You use POST not GET when sending data in the request body:
Also fix your content type
Private Sub UserForm_Click()
Dim strUrl As String, hreq
strUrl = "https://charter.osp-cloud.com/ATOM/Dashboard/GetComments"
Set hreq = CreateObject("MSXML2.XMLHTTP")
With hreq
.Open "POST", strUrl, False
.SetRequestHeader "Content-Type", "application/json"
.Send "{""id"":1015998}"
End With
Debug.Print hreq.ResponseText
End Sub
or if you want to use GET then the data goes in the querystring:
Private Sub UserForm_Click()
Dim strUrl As String, hreq
strUrl = "https://charter.osp-cloud.com/ATOM/Dashboard/GetComments?id=1015998"
Set hreq = CreateObject("MSXML2.XMLHTTP")
With hreq
.Open "GET", strUrl, False
.SetRequestHeader "Content-Type", "application/json"
.Send
End With
Debug.Print hreq.ResponseText
End Sub
I send messages form Excel to telegram. It works nice.
But how can I send a photo? I don't understand it (https://core.telegram.org/bots/api#sendphoto)
Thanks for help!
My send Message:
Dim objRequest As Object
Dim strChatId As String
Dim strMessage As String
Dim strPostData As String
Dim strResponse As String
strChatId = Worksheets("Einstellungen").Cells(3, "AB")
strMessage = Report
APIcode = Worksheets("Einstellungen").Cells(2, "AB")
strPostData = "chat_id=" & strChatId & "&text=" & strMessage
Set objRequest = CreateObject("MSXML2.XMLHTTP")
With objRequest
.Open "POST", "https://api.telegram.org/" & APIcode & "/sendMessage?", False
.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
.send (strPostData)
GetSessionId = .responseText
End With
If your code is working as-is for plain text messages then you should only need to make a couple changes to it.
You're probably currently using the API's sendMessage method, which takes the chat_id and text parameters.
You want to use the sendPhoto method, which tales the chat_id and photo parameters (but no text parameter).
So this is a bit of a shot in the dark since I've never used or heard of Telegram and I don't have a key, so I can't test it, but theoretically, you could send a photo from a URL like this:
Sub telegram_SendPhoto()
Const photoURL = "https://i.imgur.com/0eH6d1v.gif" 'URL of photo
Dim objRequest As Object, strChatId As String, APIcode As String
Dim strPostData As String, strResponse As String
strChatId = Worksheets("Einstellungen").Cells(3, "AB")
APIcode = Worksheets("Einstellungen").Cells(2, "AB")
strPostData = "chat_id=" & strChatId & "&photo=" & photoURL
Set objRequest = CreateObject("MSXML2.XMLHTTP")
With objRequest
.Open "POST", "https://api.telegram.org/" & APIcode & "/sendPhoto?", False
.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
.send (strPostData)
strResponse = .responseText
End With
MsgBox strResponse
End Sub
Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet (above), or upload a new photo using multipart/form-data. More info on Sending Files »
first time posting,
I'm trying to get the ID "dadosDoUsuario" from a website's page I have to be logged in. I got it working using "InternetExplorer.Application" object, but can't get the ID value when using "MSXML2.XMLHTTP" object. It seems it won't go past the login page, since I'm able to get other IDs from this page (example: "tituloPagina"). Could someone give a hint on how I get the data from the page after logged in? Thanks!
InternetExplorer.Application code (this one works):
Sub testIE()
Dim texto As String
Set ie = CreateObject("InternetExplorer.Application")
my_url = "https://www.nfp.fazenda.sp.gov.br/login.aspx"
With ie
.Visible = False
.Navigate my_url
Do Until Not ie.Busy And ie.readyState = 4
DoEvents
Loop
End With
ie.Document.getelementbyid("userName").Value = "MYUSERNAME"
ie.Document.getelementbyid("Password").Value = "MYPASSWORD"
ie.Document.getelementbyid("Login").Click
Do Until Not ie.Busy And ie.readyState = 4
DoEvents
Loop
ie.Document.getelementbyid("btnConsultarNFSemestre").Click
Do Until Not ie.Busy And ie.readyState = 4
DoEvents
Loop
texto = ie.Document.getelementbyid("dadosDoUsuario").innerText
MsgBox texto
ie.Quit
End Sub
MSXML2.XMLHTTP code (this one doesn't work):
Sub testXMLHTTP()
Dim xml As Object
Dim html As Object
Dim dados As Object
Dim text As Object
Set xml = CreateObject("MSXML2.XMLHTTP")
Set html = CreateObject("htmlFile")
With xml
.Open "POST", "https://www.nfp.fazenda.sp.gov.br/Login.aspx", False
.setRequestHeader "Content-Type", "text/xml"
.send "userName=MYUSERNAME&password=MYPASSWORD"
.Open "GET", "https://www.nfp.fazenda.sp.gov.br/Inicio.aspx", False
.setRequestHeader "Content-Type", "text/xml"
.send
End With
html.body.innerhtml = xml.responseText
Set objResult = html.GetElementById("dadosDoUsuario")
GetElementById = objResult.innertext
MsgBox GetElementById
End Sub
EDIT: I followed the steps suggested by #Florent B., and added a scripcontrol to get the encoded values for __VIEWSTATE, __VIEWSTATEGENERATOR and __EVENTVALIDATION. Got it working!
Sub testXMLHTTP()
Dim xml As Object
Dim html As HTMLDocument
Dim dados As Object
Dim text As Object
Dim html2 As HTMLDocument
Dim xml2 As Object
Set xml = CreateObject("Msxml2.ServerXMLHTTP.6.0")
Set html = CreateObject("htmlFile")
With xml
.Open "GET", "https://www.nfp.fazenda.sp.gov.br/Login.aspx", False
.send
End With
strCookie = xml.getResponseHeader("Set-Cookie")
html.body.innerhtml = xml.responseText
Set objvstate = html.GetElementById("__VIEWSTATE")
Set objvstategen = html.GetElementById("__VIEWSTATEGENERATOR")
Set objeventval = html.GetElementById("__EVENTVALIDATION")
vstate = objvstate.Value
vstategen = objvstategen.Value
eventval = objeventval.Value
'URL Encode ViewState
Dim ScriptEngine As ScriptControl
Set ScriptEngine = New ScriptControl
ScriptEngine.Language = "JScript"
ScriptEngine.AddCode "function encode(vstate) {return encodeURIComponent(vstate);}"
Dim encoded As String
encoded = ScriptEngine.Run("encode", vstate)
vstate = encoded
'URL Encode Event Validation
ScriptEngine.AddCode "function encode(eventval) {return encodeURIComponent(eventval);}"
encoded = ScriptEngine.Run("encode", eventval)
eventval = encoded
'URL Encode ViewState Generator
ScriptEngine.AddCode "function encode(vstategen) {return encodeURIComponent(vstategen);}"
encoded = ScriptEngine.Run("encode", vstategen)
vstategen = encoded
Postdata = "__EVENTTARGET=" & "&__EVENTARGUMENT=" & "&__VIEWSTATE=" & vstate & "&__VIEWSTATEGENERATOR=" & vstategen & "&__EVENTVALIDATION=" & eventval & "&ctl00$ddlTipoUsuario=#rdBtnNaoContribuinte" & "&ctl00$UserNameAcessivel=Digite+o+Usuário" & "&ctl00$PasswordAcessivel=x" & "&ctl00$ConteudoPagina$Login1$rblTipo=rdBtnNaoContribuinte" & "&ctl00$ConteudoPagina$Login1$UserName=MYUSERNAME" & "&ctl00$ConteudoPagina$Login1$Password=MYPASSWORD" & "&ctl00$ConteudoPagina$Login1$Login=Acessar" & "&ctl00$ConteudoPagina$Login1$txtCpfCnpj=Digite+o+Usuário"
Set xml2 = CreateObject("Msxml2.ServerXMLHTTP.6.0")
Set html2 = CreateObject("htmlFile")
With xml2
.Open "POST", "https://www.nfp.fazenda.sp.gov.br/Login.aspx", False
.setRequestHeader "Cookie", strCookie
.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
.setRequestHeader "Content-Lenght", Len(Postdata)
.send (Postdata)
End With
html2.body.innerhtml = xml2.responseText
Set objResult = html2.GetElementById("dadosDoUsuario")
GetElementById = objResult.innertext
MsgBox GetElementById
End Sub
It's possible but not that easy.
First you need to use CreateObject("Msxml2.ServerXMLHTTP.6.0") and not CreateObject("MSXML2.XMLHTTP").
Then follow these steps:
Open and send a GET to https://www.nfp.fazenda.sp.gov.br/login.aspx
Parse and store the cookie from the response header "Set-Cookie"
Parse and store the __VIEWSTATE, __VIEWSTATEGENERATOR, __EVENTVALIDATION from the HTML response
Build the data for the next query with the values parsed previously and with your user-name/password :
__EVENTTARGET:""
__EVENTARGUMENT:""
__VIEWSTATE:"..."
__VIEWSTATEGENERATOR:"..."
__EVENTVALIDATION:"..."
ctl00$ddlTipoUsuario:"#rdBtnNaoContribuinte"
ctl00$UserNameAcessivel:"Digite+o+Usuário"
ctl00$PasswordAcessivel:"x"
ctl00$ConteudoPagina$Login1$rblTipo:"rdBtnNaoContribuinte"
ctl00$ConteudoPagina$Login1$UserName:"..."
ctl00$ConteudoPagina$Login1$Password:"..."
ctl00$ConteudoPagina$Login1$Login:"Acessar"
ctl00$ConteudoPagina$Login1$txtCpfCnpj:"Digite+o+Usuário"
Open a POST to https://www.nfp.fazenda.sp.gov.br/login.aspx
Set the header "Cookie" with the cookie parsed at step 2
Set the header Content-Type: "application/x-www-form-urlencoded"
Set the header Content-Length with the length of the data
Send the POST with the data from step 4
The following is the HTML of part of a web page.
"input name="ctl00$ctl00$AllContent$ContentMain$ucMktStatCtl$txtDate" type="text"
id="ctl00_ctl00_AllContent_ContentMain_ucMktStatCtl_txtDate"
onkeypress="javascript:return fnTrapKD(event, document.getElementById('ctl00_ctl00_AllContent_ContentMain_ucMktStatCtl_butReport'))"
value="02/24/2006" class="hasDatepicker">
I tried to use the following code to access the data.
Dim strPostData As String: strPostData = "ctl00$ctl00$AllContent$ContentMain$ucMktStatCtl$txtDate=02/24/2006"
Dim xmlhttp: Set xmlhttp = CreateObject("msxml2.xmlhttp.3.0")
xmlhttp.Open "POST", "http://www.cboe.com/data/mktstat2.aspx#VIX", False
xmlhttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
xmlhttp.send (strPostData)
I am getting responsetext with 404 - File or directory not found. But the site does accept the input in a browser.
The mozilla firefox addon firebug helps to analyse the http request.
Post tab shows the parameters which are sent.
The URL should be http://www.cboe.com/data/mktstat2.aspx
Sub test()
Dim strPostData As String
strPostData = "ctl00$ctl00$AllContent$ContentMain$ucMktStatCtl$butReport=Get Report&ctl00$ctl00$AllContent$ContentMain$ucMktStatCtl$ddlNav=&ctl00$ctl00$AllContent$ContentMain$ucMktStatCtl$txtDate=05/31/2013&ctl00$ctl00$AllContent$ucHeader$CBOEHeaderSearchBox$txtHeaderSearch=Search&ctl00$ctl00$AllContent$ucHeader$ucCBOEHeaderQuoteBox$txtHeaderQuote=Quote"
Dim xmlhttp As Object
Set xmlhttp = CreateObject("msxml2.xmlhttp")
xmlhttp.Open "POST", "http://www.cboe.com/data/mktstat2.aspx", False
xmlhttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
xmlhttp.send (strPostData)
MsgBox xmlhttp.responseText
End Sub