delphiurlpascallazarus

Extract URL parameters from URL? In DELPHI


I have an incoming URL which I need to catch some parameters, our project is in Delphi. Here is what the URL looks like :

I need to get the value right after "state" and before'code'. I am using a class from System.Net.URLClient.TURI

AURL = 'https://accounts.google.com/o/oauth2/approval/v2?auto=false&response=state%3DF409B222-B0B5-4AF0-B3A2-BC64DCEDA5B6%26code%3D4%2F1AY0e-g6kT90V4_L-HN_BkljW8XCAP79bVIaoE7ZErspKCTr83teAEPxbyHs%26scope%3Dprofile%2520openid%2520https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile%26authuser%3D0%26prompt%3Dconsent&approvalCode=4%2F1AY0e-g6kT90V4_L-HN_BkljW8XCAP79bVIaoE7ZErspKCTr83teAEPxbyHs#'
uri := TUri.Create(AUrl); 
returnstate := uri.ParameterByName['state'];

When using the parameterbyname it's empty. Appreciate the help.


Solution

  • As stated in the comments, you need to decode the response parameter.

    First step is percent decoding. You can use TURLEnconding for this.

    Response := TURLEncoding.Decode(uri.ParameterByName['response']);
    

    Then, break the embedded response at the encoded & characters. There may be an easier way to do it, but you could use Pos, or a TPerlRegEx. I think a quick way would be to use a TStringList and set the & as the Delimiter character:

    ResponseParams := TStringList.Create;
    ResponseParams.Delimiter := '&';
    ResponseParams.DelimitedText := Response;
    

    Then, you have name-value pairs and a standard TStringList will separate those for you.

    ResponseParams.Values['status']