B4J Question How to get parameters from an encoded URL

wanx

New Member
Licensed User
Longtime User
When I run b4j web server, I can get the parameters with req.GetPrameter, but I can't get the correct parameters from an encoded URL.
Here is my code:
B4X:
Sub Handle(req As ServletRequest, resp As ServletResponse)
    Log(req.FullRequestURI)
    Log($"req.GetParameter("devid")=${req.GetParameter("devid")}"$)
    
    Dim params As Map = req.ParameterMap
    For Each name As String In params.Keys
        Dim values() As String = params.Get(name)
        Dim param As String = ""
        For Each value As String In values
            param = param & value
        Next
        Log($"name=${name},param=${param}"$)
    Next
End Sub

the log:
B4X:
Server started
http://127.0.0.1:8089/hello?devid=201910160002&token=e43d37cc3481ea6d
req.GetParameter("devid")=201910160002
name=devid,param=201910160002
name=token,param=e43d37cc3481ea6d

http://127.0.0.1:8089/hello?devid%3D201910160002%26token%3De43d37cc3481ea6d
req.GetParameter("devid")=
name=devid=201910160002&token=e43d37cc3481ea6d,param=

I modified the code to solve it,I don't know if there is a better way。
B4X:
Sub Handle(req As ServletRequest, resp As ServletResponse)
    Log(req.FullRequestURI)
    Log($"req.GetParameter("devid")=${req.GetParameter("devid")}"$)

    Dim params As Map = req.ParameterMap
    For Each name As String In params.Keys
        Dim values() As String = params.Get(name)
        Dim param As String = ""
        For Each value As String In values
            param = param & value
        Next
        If name.IndexOf("=") = -1 Then
            Log($"name=${name},param=${param}"$)
        Else
            getParamsFromUrlEncode(name)
        End If
        
    Next
End Sub

Sub getParamsFromUrlEncode(strencode As String)
    Dim params() As String = Regex.Split("&", strencode)
    Dim i As Int
    For i = 0 To params.Length - 1
        Dim keyvalue() As String = Regex.Split("=", params(i))
        If keyvalue.Length = 2 Then
            Log($"name=${keyvalue(0)},param=${keyvalue(1)}"$)
        Else
            Log($"can't parse:${params(i)}"$)
        End If
    Next
End Sub
 
Top