在HttpSendRequest之后获取身份验证令牌

时间:2010-04-21 19:22:58

标签: delphi token wininet

以下代码将我的应用程序登录到服务器。如果登录成功,该服务器将返回身份验证令牌。我需要使用该令牌来查询服务器以获取信息。

  egressMsg := pchar('email='+LabeledEdit1.text+'&&password='+MaskEdit1.Text+#0);
  egressMsg64 := pchar(Encode64(egressMsg));

  Reserved := 0;

  // open connection
    hInternetConn := InternetOpen('MyApp', INTERNET_OPEN_TYPE_PRECONFIG, NIL, NIL, 0);

  if hInternetConn = NIL then
  begin
    ShowMessage('Error opening internet connection');
    exit;
  end;

  // connect
  hHttpSession := InternetConnect(hInternetConn, 'myserver.com',
    INTERNET_DEFAULT_HTTP_PORT, '', '', INTERNET_SERVICE_HTTP, 0, 0);

  if hHttpSession = NIL then
  begin
    ShowMessage('Error connecting');
    exit;
  end;

  // send request
  hHttpRequest := HttpOpenRequest(hHttpSession, 'POST',
      '/myapp/login', NIL, NIL, NIL, 0, 0);

  if hHttpRequest = NIL then
  begin
    ShowMessage('Error opening request');
    exit;
  end;

  label2.caption := egressMsg64 + '    '+inttostr(length(egressMsg64));
  res := HttpSendRequest(hHttpRequest, Nil,
        DWORD(-1), egressMsg64, length(egressMsg64));

  if not res then
  begin
    ShowMessage('Error sending request ' + inttostr(GetLastError));
    exit;
  end;

  BufferSize := Length(infoBuffer);

  res := HttpQueryInfo(hHttpRequest, HTTP_QUERY_STATUS_CODE, @infoBuffer, BufferSize, Reserved);

  if not res then
  begin
    ShowMessage('Error querying request ' + inttostr(GetLastError));
    exit;
  end;

  reply := infoBuffer;
  Memo1.Lines.Add(reply);

  if reply <> '200' then
  begin
    //error here
  end;

  // how to I get the token here!!!!

  InternetCloseHandle(hHttpRequest);
  InternetCloseHandle(hHttpSession);        
  InternetCloseHandle(hInternetConn);

我如何获得该令牌?我尝试查询cookie,我尝试了InternetGetCookie()等等。 代码表示赞赏

由于

尔杰斯

修改

我发现如果您使用InternetReadFile,您可以获得该令牌。但是,该令牌以字节数组形式出现。以后很难用它将它发送到服务器......谁知道如何将字节数组转换为pchar或string?

2 个答案:

答案 0 :(得分:1)

对于正常的基于零的数组,不应该是'Chr(token2 [i-1])'吗?

或者,假设使用非unicode Delphi,您可以使用:

SetLength(strtoken, Reserved2);
CopyMemory(@strtoken[1], @token2[0], Reserved2);

注意:除非你将strtoken声明为AnsiString,否则这将在Unicode Delphi中中断 对于Unicode识别Delphi,请使用TEncoding.ASCII.GetString

答案 1 :(得分:0)

这里是:

  if not InternetReadFile(hHttpRequest, @token2, sizeof(token2), Reserved2) then
    Memo1.Lines.Add('error = ' + inttostr(GetLastError))
  else
  begin
    for i:=1 to Reserved2 do
      strtoken := strtoken + Chr(token2[i]);

    Memo1.Lines.Add('token = '+strtoken);
    Memo1.Lines.Add('recevied = '+inttostr(Reserved2));
  end;

token2是一个字节数组。