Difference between revisions of "fphttpclient"

From Free Pascal wiki
Jump to navigationJump to search
Line 45: Line 45:
 
   With TFPHttpClient.Create(Nil) do
 
   With TFPHttpClient.Create(Nil) do
 
     try
 
     try
       S:=Get(ParamStr(1));
+
       S := Get(ParamStr(1));
 
     finally
 
     finally
 
       Free;
 
       Free;
Line 70: Line 70:
 
   With TFPHttpClient.Create(Nil) do
 
   With TFPHttpClient.Create(Nil) do
 
     try
 
     try
       Respo:=TStringStream.Create('');
+
       Respo := TStringStream.Create('');
 
       FileFormPost('http://example.com/upload.php','PostFilenameParam (ex. 'file')',edtSourceFile.Text,Respo);
 
       FileFormPost('http://example.com/upload.php','PostFilenameParam (ex. 'file')',edtSourceFile.Text,Respo);
       S:=Respo.DataString;
+
       S := Respo.DataString;
 
       Respo.Destroy;
 
       Respo.Destroy;
 
     finally
 
     finally
Line 97: Line 97:
 
begin
 
begin
 
   try
 
   try
     HTTPClient:=TFPHTTPClient.Create(nil);
+
     HTTPClient := TFPHTTPClient.Create(nil);
     IPRegex:=TRegExpr.Create;
+
     IPRegex := TRegExpr.Create;
 
     try
 
     try
 
       //returns something like:
 
       //returns something like:
Line 106: Line 106:
 
       RawData:=HTTPClient.Get('http://checkip.dyndns.org');
 
       RawData:=HTTPClient.Get('http://checkip.dyndns.org');
 
       // adjust for expected output; we just capture the first IP address now:
 
       // adjust for expected output; we just capture the first IP address now:
       IPRegex.Expression:=RegExprString('\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b');
+
       IPRegex.Expression := RegExprString('\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b');
 
       //or
 
       //or
 
       //\b(?:\d{1,3}\.){3}\d{1,3}\b
 
       //\b(?:\d{1,3}\.){3}\d{1,3}\b
 
       if IPRegex.Exec(RawData) then
 
       if IPRegex.Exec(RawData) then
 
       begin
 
       begin
         result:=IPRegex.Match[0];
+
         result := IPRegex.Match[0];
 
       end
 
       end
 
       else
 
       else
 
       begin
 
       begin
         result:='Got invalid results getting external IP address. Details:'+LineEnding+
+
         result := 'Got invalid results getting external IP address. Details:'+LineEnding+
 
           RawData;
 
           RawData;
 
       end;
 
       end;
Line 121: Line 121:
 
       on E: Exception do
 
       on E: Exception do
 
       begin
 
       begin
         result:='Error retrieving external IP address: '+E.Message;
+
         result := 'Error retrieving external IP address: '+E.Message;
 
       end;
 
       end;
 
     end;
 
     end;

Revision as of 18:55, 3 January 2018

Overview

fphttpclient is supplied with FPC as part of the fcl-web package, and can be used by itself as well.

HTTPS (TLS/SSL)

Since April 2014, the trunk/development fphttpclient supports SSL/TLS connections using the OpenSSL library (will ship with version 2.8.0 and above). This requires the OpenSSL .so/.dll/.dylib library/libraries to be installed (e.g. present in your application or system directory on Windows).

  • If you do not use client side certificates, just specifying the proper port (e.g. 443 for https) is enough to enable TLS/SSL as long as you have OpenSSL libraries installed (or e.g. in the application directory)
  • If you want to use e.g. a client side certificate, do something like this:
uses ...ssockets, sslsockets..
// Callback for setting up SSL client certificate
procedure TSSLHelper.SSLClientCertSetup(Sender: TObject; const UseSSL: Boolean;
  out AHandler: TSocketHandler);
begin
  AHandler := nil;
  if UseSSL and (FClientCertificate <> '') then
  begin
    // Only set up client certificate if needed.
    // If not, let normal fphttpclient flow create
    // required socket handler
    AHandler := TSSLSocketHandler.Create;
    // Example: use your own client certificate when communicating with the server:
    (AHandler as TSSLSocketHandler).Certificate.FileName := FClientCertificate;
  end;
end;

//... and in your TFPHTTPClient creation:
myclient := TFPHTTPClient.Create(nil);
if FClientCertificate <> '' then
  myclient.OnGetSocketHandler := @SSLClientCertSetup;

Examples

Examples are included in your FPC directory: packages/fcl-web/examples/

Apart from those, please see below:

Get body of a web page via HTTP protocol

uses fphttpclient;

Var
  S : String;

begin
  With TFPHttpClient.Create(Nil) do
    try
      S := Get(ParamStr(1));
    finally
      Free;
    end;
  Writeln('Got : ',S);
end.

If you want to write even less lines of code, in FPC 2.7.1 you can use the class method:

s := TFPCustomHTTPClient.SimpleGet('http://a_site/a_page');

Upload a file using POST

Use TFPHTTPClient.FileFormPost()

uses fphttpclient;

Var
  Respo: TStringStream;
  S : String;

begin
  With TFPHttpClient.Create(Nil) do
    try
      Respo := TStringStream.Create('');
      FileFormPost('http://example.com/upload.php','PostFilenameParam (ex. 'file')',edtSourceFile.Text,Respo);
      S := Respo.DataString;
      Respo.Destroy;
    finally
      Free;
    end;
end.

Get external IP address

If your computer is connected to the internet via a LAN (cabled or wireless), the IP address of your network card most probably is not your external IP address.

You can retrieve your external IP address from e.g. your router or an external site. The code below tries to get it from an external site (thanks to JoStudio on the forum for the inspiration: [1]):

{$mode objfpc}{$H+}

uses
  Classes, SysUtils, fphttpclient, RegexPr;

function GetExternalIPAddress: string;
var
  HTTPClient: TFPHTTPClient;
  IPRegex: TRegExpr;
  RawData: string;
begin
  try
    HTTPClient := TFPHTTPClient.Create(nil);
    IPRegex := TRegExpr.Create;
    try
      //returns something like:
      {
<html><head><title>Current IP Check</title></head><body>Current IP Address: 44.151.191.44</body></html>        
      }
      RawData:=HTTPClient.Get('http://checkip.dyndns.org');
      // adjust for expected output; we just capture the first IP address now:
      IPRegex.Expression := RegExprString('\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b');
      //or
      //\b(?:\d{1,3}\.){3}\d{1,3}\b
      if IPRegex.Exec(RawData) then
      begin
        result := IPRegex.Match[0];
      end
      else
      begin
        result := 'Got invalid results getting external IP address. Details:'+LineEnding+
          RawData;
      end;
    except
      on E: Exception do
      begin
        result := 'Error retrieving external IP address: '+E.Message;
      end;
    end;
  finally
    HTTPClient.Free;
    IPRegex.Free;
  end;
end;

begin
  writeln('External IP address:');
  writeln(GetExternalIPAddress);
end.

Translate text using Google Translate

See Using Google Translate