프로그래밍 초보 탈출

Libraries/Delphi Library

[WebBrowser] Cookie Library

째즈토끼 2022. 6. 22. 23:23
unit LibInetCookie;

interface

uses
  Windows, WinInet, SysUtils, Classes, ShLwApi,

  LibString;

function INET_DecodeURL(Str: String) : String;
function INET_GetCookies(const URL: String; CookieList: TStrings) : Integer;
function INET_GetCookie(const URL: String; const CookieName: String; var CookieValue: String) : Boolean;
function INET_GetRawCookie(const URL: String) : String;
var
  Ln  : DWORD;
  R   : Boolean;
begin
  R := InternetGetCookie(PChar(URL), nil, nil, Ln);
  if R then begin
     SetLength(RESULT, Ln);
     R := InternetGetCookie(PChar(URL), nil, PChar(RESULT), Ln);
     end;

  if not R then begin
     RESULT := '';
     end;
end;

function __UnicodeChar(uCode: String) : String;
var
  C : WideString;
begin
  SetLength(C, 1);
  C[1] := WideChar(StrToIntDef('$' + uCode, $FFFF));
  RESULT := C;
end;

function INET_DecodeURL_UnicodeOnly(Str : String) : String;
var
  PT : Integer;
begin
  // 유니코드는 %uXXXX 형식으로 들어온다. (JavaScript로 세팅된 Cookie)
  RESULT := '';
  while STR <> '' do begin
    PT := Pos('%u', Str);
    if PT = 0 then begin
       RESULT := RESULT + Str;
       Exit;
       end;
    if PT > 1 then begin
       RESULT := RESULT + Copy(Str, 1, PT-1);
       end;
    Delete(Str, 1, PT+1);
    if Length(Str) < 4 then begin
       // Error
       Exit;
       end;

    RESULT := RESULT + __UnicodeChar(Copy(Str,1,4));
    Delete(Str, 1, 4);
    end;
end;
function INET_DecodeURL(Str: String) : String;
begin
// 유니코드는 %uXXXX 형식으로 들어온다. (JavaScript로 세팅된 Cookie)
  if Str = '' then begin
     RESULT := '';
     Exit;
     end;

  if Pos('%u', Str) > 0 then begin
     Str := INET_DecodeURL_UnicodeOnly(Str);
     end;

  UrlUnescapeInPlace(PChar(Str), 0);
  RESULT := PChar(Str);
end;

function INET_GetCookies(const URL: String; CookieList: TStrings) : Integer;
var
  Buf : String;
  A,B : String;
begin
  Buf := INET_GetRawCookie(URL);
  RESULT := 0;

  while Buf <> '' do begin
	B := Parsing(Buf, ';');
	A := Parsing(B, '=');
	CookieList.Add(A + '=' + INET_DecodeURL(B));
        Inc(RESULT);
	end;
end;

// CookieName 은 대/소문자를 구별 해야한다.
function INET_GetCookie(const URL: String; const CookieName: String; var CookieValue: String) : Boolean;
var
  Buf : String;
  A,B : String;
begin
  Buf := INET_GetRawCookie(URL);

  while Buf <> '' do begin
	B := Parsing(Buf, ';');
	A := Parsing(B, '=');

	if A = CookieName then begin
	   CookieValue := INET_DecodeURL(B);
	   RESULT := TRUE;
	   Exit;
	   end;
	end;

  RESULT := FALSE;
end;

end.

'Libraries > Delphi Library' 카테고리의 다른 글

[IPC] Memory Map  (0) 2022.06.22
[System] Item ID List Library  (0) 2022.06.22
[WebBrowser] Internet Explorer Library  (0) 2022.06.22
[System] Window Desktop Library  (0) 2022.06.22
[DateTime] Lunar Library  (0) 2022.06.22