在TMemo中以HTML格式获取服务器响应

时间:2014-05-28 10:45:17

标签: html delphi indy

我正在制作Delphi XE5 VCL表单应用程序,我正在尝试使用TIdHTTP连接到服务器。有我的程序代码:

procedure SendData(url: string; parameters: TStringList);
var 
  client: TIdHTTP;
  IdSSLIOHandler: TIdSSLIOHandlerSocketOpenSSL;
  responceStream: TStringStream;
begin
  client := TIdHTTP.Create(nil);

  try
    IdSSLIOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
    try
      responceStream := TStringStream.Create;
      try
        client.IOHandler := IdSSLIOHandler;
        client.Post(url, parameters, responceStream);
        memo.Lines.Add(client.Post(url, parameters, responceStream));
      finally
        responceStream.Free;
      end;
    finally
      IdSSLIOHandler.Free;
    end;
  finally
    client.Free;
  end;
end;

我收到的消息是:'HTTP / 1.1 200 OK'但我正在尝试接收的是响应是服务器作为响应发送到的页面的HTML。任何想法我该怎么做。

1 个答案:

答案 0 :(得分:2)

试试那些:

Uses
  IdBaseComponent, IdTCPConnection, IdTCPClient, IdHTTP, IdComponent, StrUtils;

function PostData(const AURL: string; AParamList: TStrings): string;
var
  _idHTTP: TIdHTTP;
begin
  _idHTTP := TIdHTTP.Create(nil);
  try
    _idHTTP.Request.UserAgent :=
      'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0';
    _idHTTP.Request.ContentType :=
      'application/json, text/javascript, */*; q=0.01';
    _idHTTP.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(_idHTTP);
    Result := _idHTTP.Post(AURL, AParamList);
  finally
    FreeAndNil(_idHTTP);
  end;
end;

function PostData(const AURL: string; AParamList: TStringList): string;
var
  _idHTTP: TIdHTTP;
  _ResultStream: TStringStream;
  _IdSSLIOHandler: TIdSSLIOHandlerSocketOpenSSL;
begin
  _ResultStream := TStringStream.Create('', TEncoding.UTF8);
  _idHTTP := TIdHTTP.Create(nil);
  _IdSSLIOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
  try
    _idHTTP.IOHandler := _IdSSLIOHandler;
    _idHTTP.Request.UserAgent :=
      'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0';
    _idHTTP.Request.ContentType :=
      'application/json, text/javascript, */*; q=0.01';
    _idHTTP.Post(AURL, AParamList, _ResultStream);
    _ResultStream.Position := 0;
    Result := _ResultStream.DataString;
  finally
    FreeAndNil(_ResultStream);
    FreeAndNil(_idHTTP);
    FreeAndNil(_IdSSLIOHandler);
  end;
end;


procedure TForm1.BitBtn1Click(Sender: TObject);
var
  _ParamList: TStringList;
begin
  _ParamList := TStringList.Create;
  try
    _ParamList.Add('paramname1=param_value1');
    _ParamList.Add('paramname2=param_value2');
    Memo1.text := PostData('http://someurl.com', _ParamList);
  finally
    FreeAndNil(_ParamList);
  end;
end;

当函数返回字符串时,应该很容易添加到备忘录中。