SOAP through VBA - vba

I am attempting to pull the info that the following site pulls: http://gis.calhouncounty.org/ParcelViewer/index.html. If you type in PPIN 66078 and then click Property Taxes, it will bring up data. I am attempting to recreate this SOAP request in VBA, but unsuccessfully. It calls the service, but all data in the response is blank. I got so frustrated that I even recreated the full header set, to no avail. Maybe there is a cookie issue, but the cookies on my computer don't seem to expire quickly. Here's what I have in the extract:
URL = "http://gis.calhouncounty.org/wsCalhounParcel2/Inquiry.asmx?WSDL"
method = "getTaxBill"
parcel = Range("A" & currentrow).Value
SoapRequest = SoapRequest & "<?xml version=""1.0"" encoding=""utf-8""?><soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""> "
SoapRequest = SoapRequest & "<soap:Body>"
SoapRequest = SoapRequest & "<tns:" & method & " xmlns:tns=""http://gis.calhouncounty.org"">"
SoapRequest = SoapRequest & "<tns:PPIN>" & parcel & "</tns:PPIN>"
SoapRequest = SoapRequest & "</tns:" & method & ">"
SoapRequest = SoapRequest & "</soap:Body>"
SoapRequest = SoapRequest & "</soap:Envelope>"
Set objHTTP = CreateObject("Msxml2.XMLHTTP")
objHTTP.Open "POST", URL, False
objHTTP.setRequestHeader "Host", "gis.calhouncounty.org"
objHTTP.setRequestHeader "Connection", "keep-alive"
objHTTP.setRequestHeader "Content-Length", SoapRequestLen
objHTTP.setRequestHeader "Origin", "http://gis.calhouncounty.org"
objHTTP.setRequestHeader "X-Requested-With", "ShockwaveFlash/17.0.0.169"
objHTTP.setRequestHeader "SOAPAction", "http://gis.calhouncounty.org/" & method
objHTTP.setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"
objHTTP.setRequestHeader "Content-Type", "text/xml; charset=utf-8"
objHTTP.setRequestHeader "Accept", "*/*"
objHTTP.setRequestHeader "Referer", "http://gis.calhouncounty.org/ParcelViewer"
objHTTP.setRequestHeader "Accept-Encoding", "gzip, deflate"
objHTTP.setRequestHeader "Accept-Language", "en-US,en;q=0.8"
objHTTP.setRequestHeader "Cookie", "ASPSESSIONIDAABARSAB=DIIJLAGCFJKDFKBCDNMMLEIB; ASPSESSIONIDAAACQSBA=BKAJPFCDCAJLBAKFFBACBMGC; ASPSESSIONIDCCCBRTBA=DKJPBAPDNLIFBOJGCPEDMAHG; __utma=262294995.1570768928.1429018531.1429018531.1430173329.2; __utmc=262294995; __utmz=262294995.1430173329.2.2.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); ASPSESSIONIDAQTRATAB=OHCBMBMCNALFKOCODDMIAHIA; _ga=GA1.2.90452212.1429018592; __utmt=1; __utma=167846455.90452212.1429018592.1430173349.1430248358.4; __utmb=167846455.1.10.1430248358; __utmc=167846455; __utmz=167846455.1430173349.3.3.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided)"
objHTTP.send SoapRequest
Any help is incredibly appreciated!
-Andy

You are not error checking. Adapt the following error checking to your code. err.number, err.description, err.source, file.status, file.statustext, file.getallresponseheaders.
The URL has to be 100% correct. Unlike a browser there is no code to fix urls.
The purpose of my program is to get error details.
How I get a correct URL is to type my url in a browser, navigate, and the correct URL is often in the address bar. The other way is to use Properties of a link etc to get the URL.
Also Microsoft.XMLHTTP maps to Microsoft.XMLHTTP.1.0. HKEY_CLASSES_ROOT\Msxml2.XMLHTTP maps to Msxml2.XMLHTTP.3.0. Try a later one
Try this way using xmlhttp. Edit the url's etc. If it seems to work comment out the if / end if to dump info even if seeming to work. It's vbscript but vbscript works in vb6.
On Error Resume Next
Set File = WScript.CreateObject("Microsoft.XMLHTTP")
File.Open "GET", "http://www.microsoft.com/en-au/default.aspx", False
'This is IE 8 headers
File.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 1.1.4322; .NET CLR 3.5.30729; .NET CLR 3.0.30618; .NET4.0C; .NET4.0E; BCD2000; BCD2000)"
File.Send
If err.number <> 0 then
line =""
Line = Line & vbcrlf & ""
Line = Line & vbcrlf & "Error getting file"
Line = Line & vbcrlf & "=================="
Line = Line & vbcrlf & ""
Line = Line & vbcrlf & "Error " & err.number & "(0x" & hex(err.number) & ") " & err.description
Line = Line & vbcrlf & "Source " & err.source
Line = Line & vbcrlf & ""
Line = Line & vbcrlf & "HTTP Error " & File.Status & " " & File.StatusText
Line = Line & vbcrlf & File.getAllResponseHeaders
wscript.echo Line
Err.clear
wscript.quit
End If
On Error Goto 0
Set BS = CreateObject("ADODB.Stream")
BS.type = 1
BS.open
BS.Write File.ResponseBody
BS.SaveToFile "c:\users\test.txt", 2
Also see if these other objects work.
C:\Users>reg query hkcr /f xmlhttp
HKEY_CLASSES_ROOT\Microsoft.XMLHTTP
HKEY_CLASSES_ROOT\Microsoft.XMLHTTP.1.0
HKEY_CLASSES_ROOT\Msxml2.ServerXMLHTTP
HKEY_CLASSES_ROOT\Msxml2.ServerXMLHTTP.3.0
HKEY_CLASSES_ROOT\Msxml2.ServerXMLHTTP.4.0
HKEY_CLASSES_ROOT\Msxml2.ServerXMLHTTP.5.0
HKEY_CLASSES_ROOT\Msxml2.ServerXMLHTTP.6.0
HKEY_CLASSES_ROOT\Msxml2.XMLHTTP
HKEY_CLASSES_ROOT\Msxml2.XMLHTTP.3.0
HKEY_CLASSES_ROOT\Msxml2.XMLHTTP.4.0
HKEY_CLASSES_ROOT\Msxml2.XMLHTTP.5.0
HKEY_CLASSES_ROOT\Msxml2.XMLHTTP.6.0
End of search: 12 match(es) found.
Also be aware there is a limit on how many times you can call any particular XMLHTTP object before a lockout occurs. If that happens, and it does when debugging code, just change to a different xmlhttp object
I get this running your code.
---------------------------
Windows Script Host
---------------------------
Error 0(0x0)
Source
HTTP Error 200 OK
Date: Tue, 28 Apr 2015 21:56:46 GMT
Server: Microsoft-IIS/7.5
Cache-Control: private, max-age=0
Content-Type: text/xml; charset=utf-8
X-AspNet-Version: 2.0.50727
X-Powered-By: ASP.NET
Access-Control-Allow-Origin: *
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
---------------------------
OK
---------------------------
Then I msgbox out responsebody and I have data sending cat rather than what's in your spreadsheet.

Related

REST API access via VBA returns "Invalid ID/Key" error

I am attempting to access the Appointments-Plus.com API via VBA code and am consistently being told I'm giving it an invalid site-id/key. I'm using Access from the Office365 version.
This is the relevant documentation for this API call.
When I use Postman to test out the API, I am able to successfully connect and I get data back. The URL Postman puts together is this:
https://ws.appointment-plus.com/Locations/GetLocations?Authorization:Basic=<site-ID>:<Key>&response_type=xml
My VBA code is this:
Public Sub RESTtestBigURL()
Dim responseType As String
responseType = "response_type=json"
Dim restRequest As WinHttp.WinHttpRequest
Set restRequest = New WinHttp.WinHttpRequest
Dim restResult As String
With restRequest
.Open "POST", "https://ws.appointment-plus.com/Locations/GetLocations?Authorization:Basic=<site-ID>:<Key>&response_type=xml", False
.Send
.WaitForResponse
Debug.Print ".ResponseText: " & .ResponseText
Debug.Print ".Status: " & .Status
Debug.Print ".StatusText: " & .StatusText
Debug.Print ".ResponseBody: " & .ResponseBody
End With
End Sub
I know that the first question is "are you sure you've got the <site-ID> and <key> correct???" Yes - I've copy/pasted the entire URL from Postman into my VBA code, and I've had another couple of pairs of eyeballs review it to confirm that they're still the same.
When I run that code, I get:
.ResponseText: <?xml version="1.0" encoding="utf-8" ?>
<APResponse>
<resource>customers</resource>
<action>getcustomers</action>
<request></request>
<result>fail</result>
<count>0</count>
<errors>
<error><![CDATA[Web Services authentication failed: invalid Site ID or API Key]]></error>
</errors>
</APResponse>
I've tried several other methods of accessing the API, all of which are giving me the same "Invalid ID/Key" error:
Public Sub SecondRESTtestMSXML()
Dim restRequest As MSXML2.XMLHTTP60
Set restRequest = New MSXML2.XMLHTTP60
With restRequest
.Open "GET", URL & REQUEST_GET_LOCATIONS, True
.SetRequestHeader "Authorization", "Basic" & SITE_ID & ":" & API_KEY
.SetRequestHeader "response_type", "xml"
.SetRequestHeader "Accept-Encoding", "application/xml"
.Send "{""response_type"":""JSON""&""location"":""582""}"
While .ReadyState <> 4
DoEvents
Wend
Debug.Print ".ResponseText: " & .ResponseText
Debug.Print ".Status: " & .Status
Debug.Print ".StatusText: " & .StatusText
Debug.Print ".ResponseBody: " & .ResponseBody
End With
End Sub
There is a suggestion that this is a duplicate of another question that was resolved by Base64-encoding. However, this method, while it wasn't explicit, shows that I have attempted that, too. I've added the Base64Encode function code that is called from here.
Public Sub RESTtest()
Dim restRequest As WinHttp.WinHttpRequest
Set restRequest = New WinHttp.WinHttpRequest
Dim restResult As String
With restRequest
.Open "POST", URL & REQUEST_GET_LOCATIONS, True
.SetRequestHeader "Authorization", "Basic " & SITE_ID & ":" & Base64Encode(API_KEY)
' Note call to Base64Encode() on this line ---------------- ----- ^^^^^^^^^^^^
.Option(WinHttpRequestOption_EnableRedirects) = False
.Send "{""response_type"":""JSON""}"
.WaitForResponse
Debug.Print ".ResponseText: " & .ResponseText
Debug.Print ".Status: " & .Status
Debug.Print ".StatusText: " & .StatusText
Debug.Print ".ResponseBody: " & .ResponseBody
End With
End Sub
Public Function Base64Encode(ByVal inputText As String) As String
Dim xmlDoc As Object
Dim docNode As Variant
Set xmlDoc = CreateObject("Msxml2.DOMDocument.3.0")
Set docNode = xmlDoc.createElement("base64")
docNode.DataType = "bin.base64"
docNode.nodeTypedValue = Stream_StringToBinary(inputText)
Base64Encode = docNode.Text
Set docNode = Nothing
Set xmlDoc = Nothing
End Function
Notes:
URL, REQUEST_GET_LOCATIONS, SITE_ID, and API_KEY are constants declared globally in this module for testing purposes. They, too, have all been copy/pasta'd and reviewed by several people for typos.
You may note that there are requests for responses in both XML and JSON - they're both giving me the same response.
I do have a support ticket open with Appt Plus, but I'm hoping I might get a faster response here.
Are there any obvious errors that anyone sees in this code? Are there any suggestions for other methods to attempt to call the API and get results? I've had a suggestion to write a DLL in C# and call that, however, I don't have the time to learn enough C# to make that happen, so switching languages isn't really an option here.
Additional notes:
I tried this using curl in a Powershell session, and it gives me the same result:
PS H:\> curl -method Post -uri "https://ws.appointment-plus.com/Locations/GetLocations?Authorization:Basic=<ID>:<key>&response_type=json"
The result:
StatusCode : 200
StatusDescription : OK
Content : {"resource":"locations",
"action":"getlocations",
"request":"",
"result":"fail",
"count":"0"
,"errors":[
"Web Services authentication failed: invalid Site ID or API ...
RawContent : HTTP/1.1 200 OK
Pragma: no-cache
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Date: Mon, 26 Aug 2019 17:28:41 GMT
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Set-Cooki...
Forms : {}
Headers : {[Pragma, no-cache], [Cache-Control, no-store, no-cache, must-revalidate, post-check=0,
pre-check=0], [Date, Mon, 26 Aug 2019 17:28:41 GMT], [Expires, Thu, 19 Nov 1981 08:52:00 GMT]...}
Images : {}
InputFields : {}
Links : {}
ParsedHtml : mshtml.HTMLDocumentClass
RawContentLength : 207
Per the exchanges in the comments, the main issue appears to be how the basic authorization header was being formed.
For future readers, the format for the authorization header is:
.SetRequestHeader "Authorization", "Basic " & Base64Encode(SITE_ID & ":" & API_KEY)
Also, another issue you may run into is related here. Linebreaks are inserted into the Base64 encoded string with the current approach, which won't play nice with most (if not all) APIs. A suggested fix for this would be something like:
Public Function Base64Encode(ByVal inputText As String, Optional removeBlankLines = True) As String
Dim xmlDoc As Object
Dim docNode As Variant
Set xmlDoc = CreateObject("Msxml2.DOMDocument.3.0")
Set docNode = xmlDoc.createElement("base64")
docNode.DataType = "bin.base64"
docNode.nodeTypedValue = Stream_StringToBinary(inputText)
Base64Encode = docNode.Text
Set docNode = Nothing
Set xmlDoc = Nothing
'remove blank line characters ASCII --> 10,13,10 + 13
If removeBlankLines Then Base64Encode = Replace(Replace(Replace(Base64Encode, vbCrLf, vbNullString), vbLf, vbNullString), vbCr, vbNullString)
End Function

.Write objHTTP.responseBody runtime error 3001

I have some problem with this vba code. This work from over the year. After last execution i get error in ".Write objHTTP.responseBody --runtime error 3001" I try figure out solution but I don't have any ideas. The code login in on page and download 4 files.
This is POST information:
Answers headers (250 B)
Connection
Keep-Alive
Content-Disposition
attachement; filename="baza.csv";
Content-Type
application/csv
Date
Tue, 17 Jul 2018 13:58:32 GMT
Keep-Alive
timeout=5, max=300
Server
Apache/2.4.25
Transfer-Encoding
chunked
Request Headers (976 B)
Accept
text/html,application/xhtml+xm…plication/xml;q=0.9,*/*;q=0.8
Accept-Encoding
gzip, deflate, br
Accept-Language
pl,en-US;q=0.7,en;q=0.3
Connection
keep-alive
Content-Length 38
Content-Type
application/x-www-form-urlencoded
Cookie _pk_id.50.777d=00d79034e23a5b6…41fc349c56e551787285709412976
DNT 1
Host listarobinsonow.pl
Referer https://listarobinsonow.pl/userpanel/base
Upgrade-Insecure-Requests 1
User-Agent Mozilla/5.0 (Windows NT 10.0; …) Gecko/20100101 Firefox/61.0
Code:
Sub SMB_DownloadAll()
Dim destfolder As String
destfolder = ActiveWorkbook.Path
' Autoryzacja
' Dim objHTTP As New WinHttp.WinHttpRequest
Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
URL = "http://www.listarobinsonow.pl/auth/login"
objHTTP.Open "POST", URL, False
objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
objHTTP.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
objHTTP.send ("identity=xxxxxx&password=xxxxxxx")
objHTTP.WaitForResponse
' pobranie 4 plików
SMB_Download objHTTP, "post", destfolder
SMB_Download objHTTP, "mail", destfolder
SMB_Download objHTTP, "tele", destfolder
SMB_Download objHTTP, "smss", destfolder
ThisWorkbook.Save
End Sub
Sub SMB_Download(ByRef objHTTP, base_type As String, destfolder As String)
URL = "http://www.listarobinsonow.pl/userpanel/base"
objHTTP.Open "POST", URL, False
objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
objHTTP.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
objHTTP.send ("base_type=" + base_type + "&form_type=base_download")
objHTTP.WaitForResponse
' Dim oStream1 As New ADODB.Stream
Set oStream1 = CreateObject("ADODB.Stream")
With oStream1
.Type = 1
.Open
.Write objHTTP.responseBody - the place where i get error run time 3001
.SaveToFile destfolder + "\" + base_type + ".csv", 2
End With
End Sub

Facing issue while calling a WCF webservice (under HTTPS) from VBS file

I have created a WCF WebService having multiple svc files. I call the method in the svc file from vbscript using below code:
ScriptTimeOut = 6000000
Dim soapServer, soapMessage
soapServer = "https://example.com/marketyardwebservice/SchedulerClasses/MailIntimations.svc"
soapMessage = "<s:Envelope xmlns:s=" & GetQuotedUrl("http://schemas.xmlsoap.org/soap/envelope/") & ">" & _
"<s:body>" & _
"<AuctionWinnerSendMail xmlns=" & GetQuotedUrl("http://tempuri.org/") & ">" & _
""
soapMessage = Replace(soapMessage, "'", chr(34))
Set xmlhttp = CreateObject("MSXML2.ServerXMLHTTP")
xmlhttp.SetOption 2, xmlhttp.GetOption(2)
Dim lResolve,lConnect,lSend,lReceive
lResolve = 5 * 1000
lConnect = 60 * 1000
lSend = 600 * 1000
lReceive = 600 * 1000
xmlhttp.setTimeouts lResolve, lConnect, lSend, lReceive
xmlhttp.open "POST", soapServer, False
xmlhttp.setRequestHeader "Man", POST & " " & soapServer & " HTTP/1.1"
xmlhttp.setRequestHeader "SOAPAction", "http://tempuri.org/IMailIntimations/AuctionWinnerSendMail"
xmlhttp.setRequestHeader "Content-Type", "text/xml; charset=utf-8"
xmlhttp.send(soapMessage)
Function GetQuotedUrl(ByVal value)
GetQuotedUrl = Chr(34) & value & Chr(34)
End Function
The above script gets executed properly when https is not enabled. But as soon as I enable HTTPS, I am getting the following error when the vbscript gets executed "A certificate is required to complete client authentication".
Please can anybody help me, as to how i can resolve this issue.
Thanks in advance
When you enable HTTPS on your server set Client Certificates to Ignore.

VBA and SurveyMonkey API

I have tried to do access the SM API through VBA. I have left out the JSON for now as I am already in trouble. The below is giving me "Developer Inactive" as a result, though I have another project in VB.NET (using a .NET DLL) where the same key and token works fine and I can retrieve the list of surveys.
What am I doing wrong?
Public Sub GetSMList()
Dim apiKey As String
Dim Token As String
Dim sm As Object
apiKey = "myKey"
Token = "myToken"
Set sm = CreateObject("MSXML2.XMLHTTP.6.0")
With sm
.Open "POST", "https://api.surveymonkey.net/v2/surveys/get_survey_list", False
.setRequestHeader "Authorization", "Bearer " & Token
.setRequestHeader "Content-Type", "application/json"
.send "api_key=" & apiKey
result = .responseText
End With
End Sub
You're sending your API key as part of the request body of your POST request. Add the query parameter to the URL directly and this should work.
"https://api.surveymonkey.net/v2/surveys/get_survey_list?api_key=" & apiKey
You'll then need to use "send" to send a JSON encoded request object. For get_survey_list, an empty object ("{}") will get your started.
The purpose of this code is to show error handling. This is vbscript but vbscript is pastable into VBA. The error will probably tell you why.
ALWAYS DO ERRORS on files (users delete them), networking or internet (they are not guaranteed to work), and registry reads (users delete them).
The URL has to be 100% correct. Unlike a browser there is no code to fix urls.
The purpose of my program is to get error details.
How I get a correct URL is to type my url in a browser, navigate, and the correct URL is often in the address bar. The other way is to use Properties of a link etc to get the URL.
Also Microsoft.XMLHTTP maps to Microsoft.XMLHTTP.1.0. HKEY_CLASSES_ROOT\Msxml2.XMLHTTP maps to Msxml2.XMLHTTP.3.0. Try a later one
Try this way using xmlhttp. Edit the url's etc. If it seems to work comment out the if / end if to dump info even if seeming to work. It's vbscript but vbscript works in vb6.
On Error Resume Next
Set File = WScript.CreateObject("Microsoft.XMLHTTP")
File.Open "GET", "http://www.microsoft.com/en-au/default.aspx", False
'This is IE 8 headers
File.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 1.1.4322; .NET CLR 3.5.30729; .NET CLR 3.0.30618; .NET4.0C; .NET4.0E; BCD2000; BCD2000)"
File.Send
If err.number <> 0 then
line =""
Line = Line & vbcrlf & ""
Line = Line & vbcrlf & "Error getting file"
Line = Line & vbcrlf & "=================="
Line = Line & vbcrlf & ""
Line = Line & vbcrlf & "Error " & err.number & "(0x" & hex(err.number) & ") " & err.description
Line = Line & vbcrlf & "Source " & err.source
Line = Line & vbcrlf & ""
Line = Line & vbcrlf & "HTTP Error " & File.Status & " " & File.StatusText
Line = Line & vbcrlf & File.getAllResponseHeaders
wscript.echo Line
Err.clear
wscript.quit
End If
On Error Goto 0
Set BS = CreateObject("ADODB.Stream")
BS.type = 1
BS.open
BS.Write File.ResponseBody
BS.SaveToFile "c:\users\test.txt", 2
Also see if these other objects work.
C:\Users>reg query hkcr /f xmlhttp
HKEY_CLASSES_ROOT\Microsoft.XMLHTTP
HKEY_CLASSES_ROOT\Microsoft.XMLHTTP.1.0
HKEY_CLASSES_ROOT\Msxml2.ServerXMLHTTP
HKEY_CLASSES_ROOT\Msxml2.ServerXMLHTTP.3.0
HKEY_CLASSES_ROOT\Msxml2.ServerXMLHTTP.4.0
HKEY_CLASSES_ROOT\Msxml2.ServerXMLHTTP.5.0
HKEY_CLASSES_ROOT\Msxml2.ServerXMLHTTP.6.0
HKEY_CLASSES_ROOT\Msxml2.XMLHTTP
HKEY_CLASSES_ROOT\Msxml2.XMLHTTP.3.0
HKEY_CLASSES_ROOT\Msxml2.XMLHTTP.4.0
HKEY_CLASSES_ROOT\Msxml2.XMLHTTP.5.0
HKEY_CLASSES_ROOT\Msxml2.XMLHTTP.6.0
End of search: 12 match(es) found.
Also be aware there is a limit on how many times you can call any particular XMLHTTP object before a lockout occurs. If that happens, and it does when debugging code, just change to a different xmlhttp object

VB.net sending HTTP POST request using SOCKETS

I have here a working HTTP request using SOCKETS but I do not know how to send POST requests.
Here is my code:
Dim hostName As String
Dim hostPort As Integer
Dim response As Integer
Dim iphe As IPHostEntry = Dns.GetHostEntry("www.yellowpages.com")
hostName = iphe.AddressList(0).ToString()
hostPort = 80
response = 0
Dim host As IPAddress = IPAddress.Parse(hostName)
Dim hostep As New IPEndPoint(host, hostPort)
Dim sock As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
sock.Connect(hostep)
Dim request = "GET /nationwide/mip/choice-hotels-international-462092189/send_email?lid=161004592 HTTP/1.1" & vbCr & vbLf &
"Host: 208.93.105.105" & vbCr & vbLf &
"User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36" & vbCr & vbLf &
"Connection: keep-alive" & vbCr & vbLf &
"Content-Type: application/x-www-form-urlencoded" & vbCr & vbLf &
"Content-Length: 0" & vbCr & vbLf & vbCr & vbLf
response = sock.Send(Encoding.UTF8.GetBytes(request))
response = sock.Send(Encoding.UTF8.GetBytes(vbCr & vbLf))
sock.Close()
I wanted to fill-up this webform i have mentioned in my code with these data:
email%5Bto_address%5D=test#mail.com&email%5Bfrom_name%5D=Test Name&email%5Bfrom_address%5D=test#mail.com&email%5Bnote%5D=Hello
How do I do it? I have successfully done this using HttpWebRequest using the code below:
Dim cweb As String = "http://www.yellowpages.com/novato-ca/mip/creative-memories-consultant-senior-director-461725587/send_email?lid=171673036"
Dim POST As String = "&email%5Bto_address%5D=recipient#email.com&email%5Bfrom_name%5D=Test Name&email%5Bfrom_address%5D=sender#mail.com&email%5Bnote%5D=Hello There"
Dim request As HttpWebRequest
Dim response As HttpWebResponse
request = CType(WebRequest.Create(cweb), HttpWebRequest)
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36"
request.AllowAutoRedirect = True
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = POST.Length
request.Method = "POST"
request.KeepAlive = True
Dim requestStream As Stream = request.GetRequestStream()
Dim postBytes As Byte() = Encoding.ASCII.GetBytes(POST)
requestStream.Write(postBytes, 0, postBytes.Length)
requestStream.Close()
response = CType(request.GetResponse(), HttpWebResponse)
response.Close()
But I wanted to recreate this concept by the use of SOCKETS.
If you can send a GET request using Sockets then you can certainly send a POST request.
You have to format it properly though. You can check the RFC for the whole HTTP specs.
Sample of a POST:
Dim request = "POST /nationwide/mip/choice-hotels-international-462092189/send_email?lid=161004592 HTTP/1.1" & Environment.Newline &
"Host: 208.93.105.105" & Environment.Newline &
"User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36" & Environment.Newline &
"Connection: keep-alive" & Environment.Newline &
"Content-Type: application/x-www-form-urlencoded" & Environment.Newline &
"Content-Length: 22" & Environment.Newline & Environment.Newline &
"this%20is%20the%20data"