Why will some site not load via XMLHTTPREQUEST using server side script (ASP) but I can load with javascript? - asp-classic

I'm trying to load the following test urls with Classic ASP through xmlhttprequest. But two of the sites will not load. I know the script works because I can run some sites, but some will not load. Any explanation?
I've loaded these sites with Javascript and they do load (code not included, but standard AJAX or plain JS script). So why would client-side script work and not server-side code (ASP)?
'rss_url = "https://www.nationalgeographic.com/science/2019/06/opal-fossils-reveal-new-species-dinosaur-australia-fostoria" 'THiS URL DOES NOT LOAD
rss_url = "https://www.nbcnews.com/news/us-news/ex-minneapolis-officer-who-killed-justine-damond-sentenced-12-5-n1013926" 'THIS URL DOES NOT LOAD
'rss_url = "https://www.reuters.com/article/us-usa-saudi-arms/republican-democratic-senators-seek-to-block-trump-saudi-arms-sales-idUSKCN1T61PL" 'THIS URL LOADS
Dim objHTTP
Set objHTTP = Server.CreateObject("MSXML2.XMLHTTP.6.0")
Err.Clear ' shouldn't be needed; can't hurt
ON ERROR RESUME NEXT
objHTTP.Open "GET", rss_url, False
objHTTP.setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36"
'objHTTP.setRequestHeader "Content-type", "text/html"
aErr = Array(Err.Number, Err.Description)
On Error GoTo 0
If 0 = aErr(0) Then
On Error Resume Next
objHTTP.Send
aErr = Array(Err.Number, Err.Description)
On Error GoTo 0
Select Case True
Case 0 <> aErr(0)
response.write "send failed:" & aErr(0) & aErr(1)
Case 200 = objHTTP.status
response.write rss_url & objHTTP.status & objHTTP.statusText
Case Else
response.write "further work needed:"
response.write rss_url & objHTTP.status & objHTTP.statusText
End Select
Else
response.write "open failed:" & aErr(0) & aErr(1)
End If
'ON ERROR GOTO 0
If Err.Number <> 0 Then
Response.Write "NO feed from ..."
end if
if objHTTP.Status = 200 Then sdata = BinaryToString(objHTTP.ResponseBody)
response.write sdata & "<hr>"
Set objHTTP = Nothing
Function BinaryToString(byVal Binary)
'--- Converts the binary content to text using ADODB Stream
'--- Set the return value in case of error
BinaryToString = ""
'--- Creates ADODB Stream
Dim BinaryStream
Set BinaryStream = CreateObject("ADODB.Stream")
'--- Specify stream type.
BinaryStream.Type = 1 '--- adTypeBinary
'--- Open the stream And write text/string data To the object
BinaryStream.Open
BinaryStream.Write Binary
'--- Change stream type to text
BinaryStream.Position = 0
BinaryStream.Type = 2 '--- adTypeText
'--- Specify charset for the source text (unicode) data.
BinaryStream.CharSet = "UTF-8"
'--- Return converted text from the object
BinaryToString = BinaryStream.ReadText
End Function

Try this (from this answer)
Function GetTextFromUrl(url)
Dim oXMLHTTP
Dim strStatusTest
Set oXMLHTTP = CreateObject("MSXML2.ServerXMLHTTP.3.0")
oXMLHTTP.Open "GET", url, False
oXMLHTTP.Send
If oXMLHTTP.Status = 200 Then
GetTextFromUrl = oXMLHTTP.responseText
End If
End Function
Dim sResult : sResult = GetTextFromUrl("https://www.nbcnews.com/news/us-news/ex-minneapolis-officer-who-killed-justine-damond-sentenced-12-5-n1013926")
Response.Write sResult
Works fine for me, grabs the page and displays it.

Related

Using classic ASP, how to fetch or screenscrape meta tags of html page?

Using the following code, I can reach the site, grab the data, but I cannot obtain the meta title tag. Surprisingly, I searched for methods to obtain meta tags while screenscraping with classic ASP and only found a couple of example, neither of which I could get to work.
Any assistance?
rss_url = "https://www.nationalgeographic.com/science/2019/06/opal-fossils-reveal-new-species-dinosaur-australia-fostoria/"
Set objHTTP = CreateObject("Microsoft.XMLHTTP")
objHTTP.setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36"
objHTTP.Open "GET", rss_url, False
objHTTP.Send
if objHTTP.Status = 200 Then sdata = BinaryToString(objHTTP.ResponseBody)
Set objHTTP = Nothing
Set regEx = New RegExp
regEx.Pattern = "<meta.*property=""og:image"".*content=""(.*)"".*\/>"
regEx.IgnoreCase = True
Set matches = regEx.Execute(sdata)
if matches.Count > 0 then
KeywordAl = matches(0).SubMatches(0)
response.write "Image = " & KeywordAl&"<hr>"
end if
I included the BinaryToString Function just to be complete:
Function BinaryToString(byVal Binary)
'--- Converts the binary content to text using ADODB Stream
'--- Set the return value in case of error
BinaryToString = ""
'--- Creates ADODB Stream
Dim BinaryStream
Set BinaryStream = CreateObject("ADODB.Stream")
'--- Specify stream type.
BinaryStream.Type = 1 '--- adTypeBinary
'--- Open the stream And write text/string data To the object
BinaryStream.Open
BinaryStream.Write Binary
'--- Change stream type to text
BinaryStream.Position = 0
BinaryStream.Type = 2 '--- adTypeText
'--- Specify charset for the source text (unicode) data.
BinaryStream.CharSet = "UTF-8"
'--- Return converted text from the object
BinaryToString = BinaryStream.ReadText
End Function
Try this:
Function GetTextFromUrl(url)
Dim oXMLHTTP
Dim strStatusTest
Set oXMLHTTP = CreateObject("MSXML2.ServerXMLHTTP.3.0")
oXMLHTTP.Open "GET", url, False
oXMLHTTP.Send
If oXMLHTTP.Status = 200 Then
GetTextFromUrl = oXMLHTTP.responseText
End If
End Function
Dim sResult : sResult = GetTextFromUrl("https://www.nationalgeographic.com/science/2019/06/opal-fossils-reveal-new-species-dinosaur-australia-fostoria/")
Set regEx = New RegExp
regEx.Pattern = "<meta.*property=""og:image"".*content=""(.*)"".*\/>"
regEx.IgnoreCase = True
Set matches = regEx.Execute(sResult)
if matches.Count > 0 then
KeywordAl = matches(0).SubMatches(0)
response.write "Image = " & KeywordAl&"<hr>"
end if
For me this outputs for that page:
Image = https://www.nationalgeographic.com/content/dam/science/2019/05/22/gemstone-dino/og-fostoria_final.ngsversion.1559624211907.adapt.1900.1.jpg
edit: Added some debugging info here. Try this snippet and see what it says about your TLS version - it is possible this site refuses connections below a certain TLS level.
Set objHttp = Server.CreateObject("WinHTTP.WinHTTPRequest.5.1")
objHttp.open "GET", "https://howsmyssl.com/a/check", False
objHttp.Send
Response.Write objHttp.responseText
Set objHttp = Nothing
Response.End

Classic ASP code to download .CSV file

I have a website written in Classic ASP
One page creates a .CSV file from a SQL database and stores it in the root directory along with a "Click Here" link to download it to the users PC
It has been working fine for many years and is still working fine when downloading small files, but now it comes up with a "THIS PAGE CAN'T BE DISPLAYED" error when downloading a .csv file (in this example) of some 785 records
The code is pretty short as below with the one Private Sub that does the download
<%#Language="VBScript"%>
<%Reponse.Buffer = True%>
<%
On Error Resume Next
Dim strPath
strPath = CStr(Request.QueryString("File"))
'-- do some basic error checking for the QueryString
If strPath = "" Then
Response.Clear
Response.Write("No file specified.")
Response.End
ElseIf InStr(strPath, "..") > 0 Then
Response.Clear
Response.Write("Illegal folder location.")
Response.End
ElseIf Len(strPath) > 1024 Then
Response.Clear
Response.Write("Folder path too long.")
Response.End
Else
Call DownloadFile(strPath)
End If
Private Sub DownloadFile(file)
'--declare variables
Dim strAbsFile
Dim strFileExtension
Dim objFSO
Dim objFile
Dim objStream
'-- set absolute file location
strAbsFile = Server.MapPath(file)
'-- create FSO object to check if file exists and get properties
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
'-- check to see if the file exists
If objFSO.FileExists(strAbsFile) Then
Set objFile = objFSO.GetFile(strAbsFile)
'-- first clear the response, and then set the appropriate headers
Response.Clear
'-- the filename you give it will be the one that is shown
' to the users by default when they save
Response.AddHeader "Content-Disposition", "attachment; filename=" & objFile.Name
Response.AddHeader "Content-Length", objFile.Size
Response.ContentType = "application/octet-stream"
Set objStream = Server.CreateObject("ADODB.Stream")
objStream.Open
'-- set as binary
objStream.Type = 1
Response.CharSet = "UTF-8"
'-- load into the stream the file
objStream.LoadFromFile(strAbsFile)
'-- send the stream in the response
Response.BinaryWrite(objStream.Read)
objStream.Close
Set objStream = Nothing
Set objFile = Nothing
Else 'objFSO.FileExists(strAbsFile)
Response.Clear
Response.Write("No such file exists.")
End If
Set objFSO = Nothing
End Sub
%>
So something has changed in recent months
Ay advice much appreciated
Thanks in advance
Your IIS version and configuration might be needed to help but I know IIS6 introduced a 4MB limit to BinaryWrite. Try sending your file in chunks instead.
<% Response.Buffer = False %>
...
With Server.CreateObject("ADODB.Stream")
.Open
.Type = 1
.LoadFromFile strPath
' Send 256K chunks...
Const intChunkSize = 262144
Do While Response.IsClientConnected And (.Position < .Size)
Response.BinaryWrite .Read(intChunkSize)
Loop
.Close
End With

How to upload file using vba with Access 2010

I am trying to use vba/XMLHTTP in an Access 2010 database to upload a file. While it is going through the process and I'm not receiving any errors, nothing ends up on my web site.
Here's the code which is called using:
response = HTTP_FileUpload(ShowName, "www.website_name","POST")
Public Function HTTP_FileUpload(FileName As String, ByVal pUrl As String, _
Optional ByVal pMethod As String = "GET") As String
Dim strResponse As String
On Error GoTo ErrorHandler
Dim xmlStream As Object
Set xmlStream = CreateObject("ADODB.Stream")
xmlStream.Mode = 3 ' //read write
xmlStream.Type = adTypeBinary
xmlStream.Open
xmlStream.LoadFromFile FileName
Dim objHttp As Object
Set objHttp = CreateObject("MSXML2.XMLHTTP")
objHttp.Open pMethod, pUrl, False
Debug.Print "file Name is " & FileName & " Size of file is " & xmlStream.Size
objHttp.setRequestHeader "Content-Type", "text/generic"
objHttp.setRequestHeader "Content-Length", xmlStream.Size
objHttp.send
strResponse = objHttp.responseText
HTTP_FileUpload = strResponse
Set objHttp = Nothing
Exit Function
ErrorHandler:
MsgBox "Error - code is " & Err.Number & " - " & Err.Description
End Function

how to read a .txt file from different server in classic asp?

I´m reading a text file from my server as I should with the below, but I wonder how I can read a txt file from a different server? What do I need to do to get it working?
Set fs=Server.CreateObject("Scripting.FileSystemObject")
Set f=fs.OpenTextFile(Server.MapPath("files.txt"), 1)
do while f.AtEndOfStream = false
Response.Write(f.ReadLine)
Response.Write("<br>")
loop
f.Close
Set f=Nothing
Set fs=Nothing
So this is working as it should, but I want to change the files.txt to http://www.somedomain.com/files.txt
Any input appreciated, thanks!
Claes , try this and let us know.
<% Option Explicit %>
<%
Const REMOTE_FILE_URL="http://www.somedomain.com/files.txt"
Call ShowRemoteFile
Sub ShowRemoteFile
Dim objXML, strContents, arrLines
Dim x
Set objXML=Server.CreateObject("Microsoft.XMLHTTP")
'read text file...
objXML.Open "GET", REMOTE_FILE_URL, False
objXML.Send
strContents=objXML.ResponseText
Set objXML=Nothing
'split into lines and read line by line...
arrLines=Split(strContents, VBCrLf)
For x=0 To UBound(arrLines)
Response.Write(arrLines(x)&"<br />")
Next
End Sub
%>
Use this function to fetch the text data (taken from here):
Function GetTextFromUrl(url)
Dim oXMLHTTP
Dim strStatusTest
Set oXMLHTTP = CreateObject("MSXML2.ServerXMLHTTP.3.0")
oXMLHTTP.Open "GET", url, False
oXMLHTTP.Send
If oXMLHTTP.Status = 200 Then
GetTextFromUrl = oXMLHTTP.responseText
End If
End Function
Dim sResult : sResult = GetTextFromUrl("http://www.somedomain.com/files.txt")

MSXML2.XMLHTTP send method works with early binding, fails with late binding

The code below works. But if I comment out the line Dim objRequest As MSXML2.XMLHTTP and uncomment the line Dim objRequest As Object it fails with the error message :
The parameter is incorrect
Why, and what (if anything) can I do about it?
Public Function GetSessionId(strApiId, strUserName, strPassword) As String
Dim strPostData As String
Dim objRequest As MSXML2.XMLHTTP
'Dim objRequest As Object '
strPostData = "api_id=" & strApiId & "&user=" & strUserName & "&password=" & strPassword
Set objRequest = New MSXML2.XMLHTTP
With objRequest
.Open "POST", "https://api.clickatell.com/http/auth", False
.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
.send strPostData
GetSessionId = .responseText
End With
End Function
Corey, yes, I know I would have to do that in order for my code to work without a reference to the MSXML type library. That's not the issue here. The code fails when using Dim objRequest As Object regardless of whether I use
Set objRequest = NEW MSXML2.XMLHTTP with the reference, or
Set objRequest = CreateObject("MSXML2.XMLHTTP") without the reference.
For some reason, this works:
Dim strPostData As String
Dim objRequest As Object
strPostData = "api_id=" & strApiId & "&user=" & strUserName & "&password=" & strPassword
Set objRequest = New MSXML2.XMLHTTP
With objRequest
.Open "POST", "https://api.clickatell.com/http/auth", False
.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
.send (strPostData)
GetSessionId = .responseText
End With
Instead of building the URL-encoded strPostData via string concatenation, it's strongly advisable to use a URL encoding function:
strPostData = "api_id=" & URLEncode(strApiId) & _
"&user=" & URLEncode(strUserName) & _
"&password=" & URLEncode(strPassword)
A couple of choices for a URLEncode() function in VBA are in this thread: How can I URL encode a string in Excel VBA?
If you use the Dim objRequest As Object then you would need to code:
Set objRequest = CreateObject("MSXML2.XMLHTTP")
I realise this is nearly identical to the code from Tomalek above (all credit due to you!), but this question helped me towards a full solution to a problem I had (Excel submitting to PHP server, then dealing with response)...so in case this is of any help to anyone else:
Sub Button1_Click2()
Dim objXMLSendDoc As Object
Set objXMLSendDoc = New MSXML2.DOMDocument
objXMLSendDoc.async = False
Dim myxml As String
myxml = "<?xml version='1.0'?><Request>Do Something</Request>"
If Not objXMLSendDoc.LoadXML(myxml) Then
Err.Raise objXMLSendDoc.parseError.ErrorCode, , objXMLSendDoc.parseError.reason
End If
Dim objRequest As MSXML2.XMLHTTP
Set objRequest = New MSXML2.XMLHTTP
With objRequest
.Open "POST", "http://localhost/SISADraftCalcs/Test2.php", False
.setRequestHeader "Content-Type", "application/xml;charset=UTF-16"
.setRequestHeader "Cache-Control", "no-cache"
.send objXMLSendDoc
End With
Dim objXMLDoc As MSXML2.DOMDocument
Set objXMLDoc = objRequest.responseXML
If objXMLDoc.XML = "" Then
objXMLDoc.LoadXML objRequest.responseText
If objXMLDoc.parseError.ErrorCode <> 0 Then
MsgBox objXMLDoc.parseError.reason
End If
End If
Dim rootNode As IXMLDOMElement
Set rootNode = objXMLDoc.DocumentElement
MsgBox rootNode.SelectNodes("text").Item(0).text
End Sub

Resources