unit unit1;
{$mode delphi}
interface
uses
Classes, SysUtils, AndroidWidget, Laz_And_Controls, fpjson, jsonparser;
type
{ TAndroidModule1 }
TAndroidModule1 = class(jForm)
btnConnect: jButton;
HttpClient1: jHttpClient;
TextView1: jTextView;
procedure AndroidModule1Create(Sender: TObject);
procedure btnConnectClick(Sender: TObject);
procedure HttpClient1RequestDone(Sender: TObject; content: RawByteString);
procedure HttpClient1CodeResult(Sender: TObject; code: Integer);
private
procedure PostData(const URL: string);
public
{public declarations}
end;
{$I settings.inc }
var
AndroidModule1: TAndroidModule1;
implementation
{$R *.lfm}
{ TAndroidModule1 }
procedure TAndroidModule1.AndroidModule1Create(Sender: TObject);
begin
if Assigned(HttpClient1) then
begin
HttpClient1.OnContentResult := HttpClient1RequestDone;
HttpClient1.OnCodeResult := HttpClient1CodeResult;
ShowMessage('HttpClient1 event handlers registered.');
end
else
begin
ShowMessage('HttpClient1 is not assigned.');
end;
end;
procedure TAndroidModule1.btnConnectClick(Sender: TObject);
begin
PostData(BaseUrl + 'oauth/token');
end;
procedure TAndroidModule1.HttpClient1CodeResult(Sender: TObject; code: Integer);
begin
if code <> 200 then
TextView1.Text := 'HTTP Error: ' + IntToStr(code);
end;
procedure TAndroidModule1.HttpClient1RequestDone(Sender: TObject; content: RawByteString);
var
JsonData: TJSONData;
AccessToken: string;
begin
ShowMessage('Request done handler triggered');
try
JsonData := GetJSON(content);
try
AccessToken := JsonData.FindPath('access_token').AsString;
if AccessToken = '' then
AccessToken := JsonData.FindPath('data/access_token').AsString;
if AccessToken <> '' then
ShowMessage('Token received: ' + AccessToken)
else
ShowMessage('Token not found in response.');
TextView1.Text := 'Access Token : '+AccessToken;
finally
JsonData.Free;
end;
except
on E: Exception do
begin
TextView1.Text := 'Error parsing response: ' + E.Message;
end;
end;
end;
procedure TAndroidModule1.PostData(const URL: string);
begin
HttpClient1.ClearNameValueData;
HttpClient1.AddNameValueData('grant_type', 'password');
HttpClient1.AddNameValueData('username', UserName);
HttpClient1.AddNameValueData('password', Password);
HttpClient1.AddNameValueData('client_id', 'farm');
HttpClient1.AddNameValueData('scope', 'farm_manager');
HttpClient1.AddClientHeader('Content-Type', 'application/x-www-form-urlencoded');
HttpClient1.AddClientHeader('Accept', 'application/json');
try
HttpClient1.PostNameValueDataAsync(URL);
ShowMessage('POST request sent.' + inttostr(HttpClient1.GetResponseCode())) ;
except
on E: Exception do
begin
TextView1.Text := 'Error: ' + E.Message;
end;
end;
end;
end.