[fpc-pascal] How To: Use lib curl example

Anthony Walter sysrpl at gmail.com
Tue Sep 28 02:01:00 CEST 2021


I was having some problems using vanilla sockets and OpenSSL to read a few
specific web pages using HTTPS. Normally I don't have any problems
using HTTPS, but with a few sites my code was not working. I ending up
finding the RTL unit LibCurl in one of the FPC packages and got it working
without too much trouble. LibCurl is a library allowing programmers to get
the functionality of the curl program without launching an external process.

If anyone is interested, here is a small bit of code to GET a page over
HTTP or HTTPS using LibCurl.

Interface:

function CurlGet(const Url: string; out Data: string; UserAgent: string =
''): Boolean;

Implementation:

uses
  LibCurl;

function WriteData(Ptr: PChar; MemberSize, MemberCount: UIntPtr; var Data:
string): UIntPtr; cdecl;
var
  S: string;
begin
  SetString(S, Ptr, MemberSize * MemberCount);
  Data := Data + S;
  Result := MemberSize * MemberCount;
end;

function CurlGet(const Url: string; out Data: string; UserAgent: string =
''): Boolean;
var
  Curl: PCURL;
begin
  Data := '';
  Result := False;
  if Url = '' then
    Exit;
  Curl := curl_easy_init();
  if Curl = nil then
    Exit;
  try
    curl_easy_setopt(curl, CURLOPT_URL, [PChar(Url)]);
    if UserAgent <> '' then
      curl_easy_setopt(curl, CURLOPT_USERAGENT, [PChar(UserAgent)]);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, [@WriteData]);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, [@Data]);
    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, [0]);
    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, [0]);
    Result := curl_easy_perform(curl) = CURLE_OK;
  finally
    curl_easy_cleanup(Curl);
  end;
end;
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20210927/a80c51fa/attachment.htm>


More information about the fpc-pascal mailing list