how to do http request using libreoffice basic macros - httprequest

I want to write a macro on a LibreOffice spreadsheet, to send an HTTP request to an web URL and receive a JSON like response. Can i do it with LibreOffice basic macro programming? Where can i get information about the API.
I really appreciate any tips.
Thanks

I'm too late to help Antonio, but for posterity...
You can call spreadsheet functions from Basic, as explained in the open office docs. Here's a simple example that invokes the WEBSERVICE() function:
Function GetWebContent(url As string) As String
On Error GoTo ErrorHandler
Dim funtionAccess As Object
functionAccess = createUnoService("com.sun.star.sheet.FunctionAccess")
GetWebContent = functionAccess.callFunction("WEBSERVICE",Array(url))
Exit Function
ErrorHandler:
GetWebContent = "Error " & Err
End Function
Function Test
Dim url As String
url = "http://www.google.com"
Dim response As String
response = GetWebContent(url)
End Function

Related

VBA Excel: Retrieve/display email using Gmail API on excel

I research regarding retrieving or displaying emails from gmail without using outlook and it led me here on using Gmail API. I'm confused because I don't have idea on how to solve my problem.
Here's the code:
Attribute VB_Name = "Gmail"
' Setup client and authenticator (cached between requests)
Private pGmailClient As WebClient
Private Property Get GmailClient() As WebClient
If pGmailClient Is Nothing Then
' Create client with base url that is appended to all requests
Set pGmailClient = New WebClient
pGmailClient.BaseUrl = "https://www.googleapis.com/gmail/v1/"
' Use the pre-made GoogleAuthenticator found in authenticators/ folder
' - Automatically uses Google's OAuth approach including login screen
' - Get API client id and secret from https://console.developers.google.com/
' - https://github.com/timhall/Excel-REST/wiki/Google-APIs for more info
Dim Auth As New GoogleAuthenticator
Auth.Setup CStr(Credentials.Values("Google")("id")), CStr(Credentials.Values("Google")("secret"))
Auth.AddScope "https://www.googleapis.com/auth/gmail.readonly"
Auth.Login
Set pGmailClient.Authenticator = Auth
End If
Set GmailClient = pGmailClient
End Property
' Load messages for inbox
Function LoadInbox() As Collection
Set LoadInbox = New Collection
' Create inbox request with userId and querystring for inbox label
Dim Request As New WebRequest
Request.Resource = "users/{userId}/messages"
Request.AddUrlSegment "userId", "me"
Request.AddQuerystringParam "q", "label:inbox"
Dim Response As WebResponse
Set Response = GmailClient.Execute(Request)
If Response.StatusCode = WebStatusCode.Ok Then
Dim MessageInfo As Dictionary
Dim Message As Dictionary
For Each MessageInfo In Response.Data("messages")
' Load full messages for each id
Set Message = LoadMessage(MessageInfo("id"))
If Not Message Is Nothing Then
LoadInbox.Add Message
End If
Next MessageInfo
End If
End Function
' Load message details
Function LoadMessage(MessageId As String) As Dictionary
Dim Request As New WebRequest
Request.Resource = "users/{userId}/messages/{messageId}"
Request.AddUrlSegment "userId", "me"
Request.AddUrlSegment "messageId", MessageId
Dim Response As WebResponse
Set Response = GmailClient.Execute(Request)
If Response.StatusCode = WebStatusCode.Ok Then
Set LoadMessage = New Dictionary
' Pull out relevant parts of message (from, to, and subject from headers)
LoadMessage.Add "snippet", Response.Data("snippet")
Dim Header As Dictionary
For Each Header In Response.Data("payload")("headers")
Select Case Header("name")
Case "From"
LoadMessage.Add "from", Header("value")
Case "To"
LoadMessage.Add "to", Header("value")
Case "Subject"
LoadMessage.Add "subject", Header("value")
End Select
Next Header
End If
End Function
Sub Test()
Dim Message As Dictionary
For Each Message In LoadInbox
Debug.Print "From: " & Message("from") & ", Subject: " & Message("subject")
Debug.Print Message("snippet") & vbNewLine
Next Message
End Sub
I'm using the blank file from this GitHub Link that enables this code above. I was stuck on this error:
Still I don't have the idea what's the output of this API because it's my first time using this one. I have my id and secret already from Gmail API i just removed it from the code. I guess it was really hard if I don't have someone I can do brainstorming regarding on this matter.
Hoping someone have encountered this problem or anyone is interested. Thanks.

Visual studio 2008 express crashes when writing method call

I'm using to Google Calendar API v3 and following the samples to create the windows form application I need. I have an issue in the getAuthorization method provided in the sample.
Basically whenever I write down aut.RefreshToken(... Visual studio crashes
Here's my getAuthorization method:
Private Shared Function GetAuthorization(ByVal arg As NativeApplicationClient) As IAuthorizationState
Dim scopes() As String = { _
CalendarService.Scopes.Calendar.GetStringValue, _
CalendarService.Scopes.CalendarReadonly.GetStringValue _
}
' Get the auth URL:
Dim state As IAuthorizationState = New AuthorizationState(scopes)
state.Callback = New Uri(NativeApplicationClient.OutOfBandCallbackUrl)
Dim refreshToken As String = GetRefreshToken()
If refreshToken <> "" Then
state.RefreshToken = refreshToken
'If arg.RefreshToken(state) Then
' SaveRefreshToken(refreshToken)
' Return state
'End If
End If
Dim authUri As Uri = arg.RequestUserAuthorization(state)
' Request authorization from the user (by opening a browser window):
Process.Start(authUri.ToString())
Dim authCode As String = ""
While authCode = ""
authCode = InputBox("Paste the code provided by Google here:", "Verification code")
End While
' Retrieve the access token by using the authorization code:
Dim result = arg.ProcessUserAuthorization(authCode, state)
SaveRefreshToken(refreshToken)
Return result
End Function
As it can be seen, the arg.RefreshToken block has been commented. If I try to uncomment it or writing it again, VS crashes.
I have to point out that I've tried this code on VS Pro 2010 and worked without any problems
Compiling the method in a dll on its own in VS 2010 worked as I expected, however if anyone ever encountered anything similar, I would appreciate any help as this solution is far from ideal.

Put a VBA Class into Action

My question relates to the question: JSON import to Excel
I understand most of what this post is saying, but I don't understand how to put it together in an excel module or class module. Would someone please help me to understand how I can assemble this beast to achieve my purpose?
EDIT 29-5-14 # 7.44AM -
Here is the try which I have done so far:
Installed as ClassModule syncWebRequest
'BEGIN CLASS syncWebRequest
Private Const REQUEST_COMPLETE = 4
Private m_xmlhttp As Object
Private m_response As String
Private Sub Class_Initialize()
Set m_xmlhttp = CreateObject("Microsoft.XMLHTTP")
End Sub
Private Sub Class_Terminate()
Set m_xmlhttp = Nothing
End Sub
Property Get Response() As String
Response = m_response
End Property
Property Get Status() As Long
Status = m_xmlhttp.Status
End Property
Public Sub AjaxPost(Url As String, Optional postData As String = "")
m_xmlhttp.Open "POST", Url, False
m_xmlhttp.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
m_xmlhttp.setRequestHeader "Content-length", Len(postData)
m_xmlhttp.setRequestHeader "Connection", "close"
m_xmlhttp.send (postData)
If m_xmlhttp.readyState = REQUEST_COMPLETE Then
m_response = m_xmlhttp.responseText
End If
End Sub
Public Sub AjaxGet(Url As String)
m_xmlhttp.Open "GET", Url, False
m_xmlhttp.setRequestHeader "Connection", "close"
m_xmlhttp.send
If m_xmlhttp.readyState = REQUEST_COMPLETE Then
m_response = m_xmlhttp.responseText
End If
End Sub
'END CLASS syncWebRequest
Installed as Module Test
Sub Test()
Dim request As New syncWebRequest
request.AjaxGet "http://crimson/php/SiteEnquiryAjax.php?action=aisFeed&brandCode=s&siteID=0625?format=json"
Dim json As String
json = request.Response
End Sub
I'm used to working with normal modules, but have not had to work with a class module before. I am therefore trying to understand this and translate it to meet my requirements, but forgive me if I am making it a chunkier job than one would expect.
I'm trying to query data from a local webservice that returns JSON. The webservice returns data based on an ID (e.g. 0656) in the form of:
{"total":"1","results":[{"brandName":"ABC","brandingName":"Cat","siteCategory":"Production","siteName":"Scrubbed","streetAddress":"ABC RD, SUBURB, VIC 3000","siteState":"VIC","phoneNumber":"03 0909 0909","mobileNumber":"0409 090 909","faxNumber":"03 9090 9090","applicationServer":"CAT0656ABC001","dateOpened":"1979-08-21","siteNotice":"","lastContact":"2014-05-19 04:36:31",}]}
My objective is to put this in a spreadsheet where the user can enter the sites ID (e.g. 0656) and the spreadsheet will then be able to pull and respond with data as exampled above.
EDIT 29-5-14 # 8.42AM -
Updated Module Test - my intention here was to test the parser exampled in the linked question, however when I now run the macro I receive an error. My understanding is that this may be the missing piece of what I'm trying to achieve. I have now commented out the added items to stop error occurring.
Sub Test()
Dim request As New syncWebRequest
request.AjaxGet "http://crimson/php/SiteEnquiryAjax.php?action=aisFeed&brandCode=s&siteID=0625"
Dim json As String
json = request.Response
'Set clients = parser.Parse(request.Response)
'For Each client In clients
'Name = client("Name")
'State = client("siteState")
'street = client("Address")("Street")
'suburb = client("Address")("Suburb")
'city = client("Address")("City")
'Next
End Sub
EDIT 29-5-14 # 9.40AM -
To put it another way... I want to turn this: HTTP Result of "url/SiteEnquiryAjax.php?action=aisFeed&brandCode=s&siteID=0656"
{"total":"1","results":[{"brandName":"ABC","brandingName":"Cat","siteCategory":"Production","siteName":"Scrubbed","streetAddress":"ABC RD, SUBURB, VIC 3000","siteState":"VIC","phoneNumber":"03 0909 0909","mobileNumber":"0409 090 909","faxNumber":"03 9090 9090","applicationServer":"CAT0656ABC001","dateOpened":"1979-08-21","siteNotice":"","lastContact":"2014-05-19 04:36:31",}]}
Into this: Excel Output
Without knowing the exact details of the error you are receiving, I've used vba-json before and I think you're not instantiating the parser before using it:
Dim parser As New JSONLib
Set clients = parser.parse(Request.Response)
As far as the design of the project goes, I think you've done well to separate the Request as a Class and then making the request from a Module. I ran into many similar problems accessing Salesforce from Excel and created a library that I think may help: Excel-REST. It follows a similar idea, but separates it into three classes: Client, Request, and Response. Here's an example:
Sub RetrieveJSONSimple
Dim Client As New RestClient
Dim Response As RestResponse
Set Response = Client.GetJSON("url...")
If Response.Status = Ok Then
' Response.Data is parsed json
For Each Client in Response.Data
Name = Client("Name")
State = Client("siteState")
Street = Client("Address")("Street")
Suburb = Client("Address")("Suburb")
City = Client("Address")("City")
Next Client
End If
End Sub
Sub RetrieveJSONAdvanced
Dim Client As New RestClient
Client.BaseUrl = "http://crimson/php/"
' Can also setup authentication with HTTP Basic, OAuth, and others
Dim Request As New RestRequest
Request.Resource = "SiteEnquiryAjax.php?action=aisFeed&brandCode=s&siteID={SiteId}"
Request.AddUrlSegment "SiteId", "0625"
' GET and json are default, but can be set
Request.Method = httpGET
Request.Format = json
Dim Response As RestResponse
Set Response = Client.Execute(Request)
' Process as before
End Sub

vbs script to send data and repeat

Does anyone have sample VBS code that sends a variable, waits response and repeat?
i have so far:
dim input
input = Inputbox ("Enter Var:" ,"Var sender...")
SourceURL = "http://example.com/someFunction.php?var="&input&""
that's it... my other code is not functional...
thanks in advance, hope anyone can help, totally lost in vbs... in windows in general...
Assuming that this is Windows Script Host, you can use the MSXML2 library.
do while true
Dim input, SourceURL
input = Inputbox ("Enter Var:" ,"Var sender...")
SourceURL = "http://www.google.co.uk/search?q=" & input
''// connect and send to server
Dim http: set http = CreateObject("MSXML2.XMLHTTP")
http.open "GET", SourceURL, false
http.send
if http.status = 200 then
''// do something with the return value if necessary
WScript.Echo http.responseText
else
''// problem?
end if
''// pause execution if you don't want to hit the server so often
WScript.Sleep 10
loop
if you're modifying things on the server, you should probably use a POST request instead of a GET request, but this should work if your server side script only accepts GET requests

Sending HTTP requests with VBA from Word

I am trying to send data from a Word document to a web page. I have found some code, pasted it into a new module, and saved it. When I run it I get "compile error, user defined type not defined"
My code:
Sub http()
Dim MyRequest As New WinHttpRequest
MyRequest.Open "GET", _
"http://www.google.com"
' Send Request.
MyRequest.Send
'And we get this response
MsgBox MyRequest.ResponseText
End Sub
A potential alternative to avoid having to select the library is to use an object i.e.
Sub http()
Dim MyRequest As Object
Set MyRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
MyRequest.Open "GET", _
"http://www.google.com"
' Send Request.
MyRequest.Send
'And we get this response
MsgBox MyRequest.ResponseText
End Sub
You need to set a reference to Microsoft WinHTTP Services in your VBA Project (Tools -> References).
Here's what it would look like:
Also, you can read more about the Microsoft WinHTTP Services, version 5.1 here.
You will need to change your references (Tools=>References in the code window). Look for Microsoft WinHTTP Services, version 5.1 (or newer) and tick the box. If you are using Vista and office 2007, you may also need to register it first. Open a command window as administrartor and paste:
>regsvr32.exe "c:\windows\system32\winhttp.dll"
It should say if it works.