### WebHandle URL with Parameter

This is an example of handling an URL with parameter.
Concept
Send a parameter to a B4J webserver and act accordingly.
The action in this example is to write the parameter to a file actions.txt in the dirapp folder.
The URL used is http://192.168.0.2:51042?GPIO18=On .
Note that the www folder is empty.
See also Hints after the B4J code.
Code B4J Non-UI App
Region Project Attributes
#CommandLineArgs:
#MergeLibraries: false
End Region
`Sub Process_Globals
Public srvr As Server
End Sub`
`Sub AppStart (Args() As String)
srvr.Initialize("srvr")
srvr.Port = 51042
srvr.StaticFilesFolder = File.Combine(File.DirApp, "www")
srvr.AddHandler("/*", "ActionHandler", False)
srvr.Start
StartMessageLoop
'For tests do not forget to kill the process
End Sub`
Code B4J Class Module Server Handler - ActionHandler.bas
`Sub Class_Globals
'No entries
End Sub`
`Public Sub Initialize
'Do nothing here
End Sub`
'Handle request from server
`Sub Handle(req As ServletRequest, resp As ServletResponse)
Try
'Get the parameter map
Dim m As Map = req.ParameterMap
'Get the keys and the values
Dim sb As StringBuilder
sb.Initialize
For i = 0 To m.size - 1
Dim key As String = m.GetKeyAt(i)
Dim values() As String = req.GetParameterValues(key)
'Action according the key, if key = XYZ then ...
'For tests log the action to a file in the dirapp folder
For j = 0 To values.Length - 1
Log($"Key=Value: ${key} = ${values(j)}"$)
sb.Append($"Key=Value: ${key} = ${values(j)};"$)
Next
File.WriteString(File.DirApp, "action.txt", $"${DateTime.Date(DateTime.Now)} ${DateTime.Time(DateTime.Now)}: ${sb.ToString}"$)
Next
resp.ContentType = "text/html"
resp.Write($"

# Action request completed

${sb.tostring}

"$)
Catch
File.WriteString(File.DirApp, "action.txt", $"${DateTime.Date(DateTime.Now)} ${DateTime.Time(DateTime.Now)}: ${LastException.Message}"$)
resp.Status = 404
resp.ContentType = "text/html"
resp.Write($"

# Action request Error

Error:${LastException}"$)
End Try
End Sub`
Hints
Place request to the B4J Server via Python
Example placing a request using Python instead via Webbrowser.
import requests
url = 'http://192.168.0.17:51042?GPIO20=ON'
response = requests.post(url)
print(response.text)
The result is:
<b>Action request completed.</b><br/>
-----------------
(program exited with code: 0)
Press return to continue
Additional Parameter
To put additional parameter, use like:
http://192.168.0.17:51042/?GPIO18=ON&GPIO12=OFF

Changed: 2017-12-27 16:19, Category: WebApps, File: T6C277M2085.htm, ID: 2085