Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Posting Data with Indy and Receiving it to TWebBrowser

I am trying to post data to bing with this code

function PostExample: string;
var
  lHTTP: TIdHTTP;
  lParamList: TStringList;
begin
  lParamList := TStringList.Create;
  lParamList.Add('q=test');

  lHTTP := TIdHTTP.Create(nil);
  try
    Result := lHTTP.Post('http://www.bing.com/', lParamList);
  finally

    FreeAndNil(lHTTP);
    FreeAndNil(lParamList);

  end;
end;

And then, how can I get the result to the TWebBrowser and display it?

like image 942
CRQ Avatar asked Feb 13 '12 20:02

CRQ


2 Answers

Try LoadDocFromString:

procedure LoadBlankDoc(ABrowser: TWebBrowser);
begin
  ABrowser.Navigate('about:blank');
  while ABrowser.ReadyState <> READYSTATE_COMPLETE do
  begin
    Application.ProcessMessages;
    Sleep(0);
  end;
end;

procedure CheckDocReady(ABrowser: TWebBrowser);
begin
  if not Assigned(ABrowser.Document) then
    LoadBlankDoc(ABrowser);
end;

procedure LoadDocFromString(ABrowser: TWebBrowser; const HTMLString: wideString);
var
  v: OleVariant;
  HTMLDocument: IHTMLDocument2;
begin
  CheckDocReady(ABrowser);
  HTMLDocument := ABrowser.Document as IHTMLDocument2;
  v := VarArrayCreate([0, 0], varVariant);
  v[0] := HTMLString;
  HTMLDocument.Write(PSafeArray(TVarData(v).VArray));
  HTMLDocument.Close;
end;
like image 185
kobik Avatar answered Nov 10 '22 10:11

kobik


Or you can use the memory streams for loading

uses
  OleCtrls, SHDocVw, IdHTTP, ActiveX;

function PostRequest(const AURL: string; const AParams: TStringList;
  const AWebBrowser: TWebBrowser): Boolean;
var
  IdHTTP: TIdHTTP;
  Response: TMemoryStream;
begin
  Result := True;
  try
    AWebBrowser.Navigate('about:blank');
    while AWebBrowser.ReadyState < READYSTATE_COMPLETE do
      Application.ProcessMessages;

    Response := TMemoryStream.Create;
    try
      IdHTTP := TIdHTTP.Create(nil);
      try
        IdHTTP.Post(AURL, AParams, Response);
        if Response.Size > 0 then
        begin
          Response.Position := 0;
          (AWebBrowser.Document as IPersistStreamInit).Load(
            TStreamAdapter.Create(Response, soReference));
        end;
      finally
        IdHTTP.Free;
      end;
    finally
      Response.Free;
    end;
  except
    Result := False;
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  Params: TStringList;
begin
  Params := TStringList.Create;
  try
    Params.Add('q=test');
    if not PostRequest('http://www.bing.com/', Params, WebBrowser1) then
      ShowMessage('An unexpected error occured!');
  finally
    Params.Free;
  end;
end;
like image 4
TLama Avatar answered Nov 10 '22 08:11

TLama