登录 用户中心() [退出] 后台管理 注册
   
您的位置: 首页 >> SoftHub关联区 >> 主题: [lazarus/delphi]lazarus 如何访问 http? [未测试]     [回主站]     [分站链接]
[lazarus/delphi]lazarus 如何访问 http? [未测试]
clq
浏览(232) - 2020-05-27 12:31:57 发表 编辑

关键字: lazarus

[lazarus/delphi]lazarus 如何访问 http?

发现 lazarus 的很多库居然比 delphi 完善。以下这个就是 delphi 中没有的。

https://wiki.lazarus.freepascal.org/fphttpclient

fphttpclient
Contents

1 Overview
2 HTTPS (TLS/SSL)
3 Examples
3.1 Get body of a web page via HTTP protocol
3.2 Download a file via HTTP protocol
3.3 Upload a file using POST
3.4 Form data and encoding
3.5 Get external IP address
3.6 Translate text using Google Translate
4 External links

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 fewer lines of code, in FPC 2.7.1 you can use the class method:

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

Download a file via HTTP protocol

Let's show you the simplest example using HTTP only. This example retrieves just an html page and writes it to the screen.

It uses one of the class Get methods of TfpHttpClient. You don't need to create and free the class. There are several overloads for e.g. TStrings or TStream (file) as well:

program dl_fphttp_a;
{$mode delphi}{$ifdef windows}{$apptype console}{$endif}
uses
fphttpclient;
begin
writeln(TFPHttpClient.SimpleGet('http://example.com'));
end.

That's all! For simple purposes this will suffice. You can even use it for HTTPS, which needs just the inclusion of two units:

program dl_fphttp_b;

{$mode delphi}{$ifdef windows}{$apptype console}{$endif}

uses
fphttpclient,
fpopenssl,
openssl;

begin
writeln(TFPHttpClient.SimpleGet('https://freepascal.org'));
end.

This really is all there is to do in simple scenarios, usually if you have enough control.

But there are some caveats with this code. The foremost one being that this code does not allow for redirects. Let me demo that:

program dl_fphttp_redirect_error;
{$mode delphi}{$ifdef windows}{$apptype console}{$endif}
uses
sysutils, fphttpclient, fpopenssl, openssl;
begin
try
writeln(TFPHttpClient.SimpleGet('https://google.com'));
except on E:EHttpClient do
writeln(e.message) else raise;
end;
end.

Because the Google URL uses redirects, there is an exception: "Unexpected response status code: 301". In such a case we need more control, which I will show you in the next example:

program dl_fphttp_c;

{$mode delphi}{$ifdef windows}{$apptype console}{$endif}

uses
classes,
fphttpclient,
fpopenssl,
openssl;

var
Client: TFPHttpClient;

begin

{ SSL initialization has to be done by hand here }
InitSSLInterface;

Client := TFPHttpClient.Create(nil);
try
{ Allow redirections }
Client.AllowRedirect := true;
writeln(Client.Get('https://google.com/'));
finally
Client.Free;
end;
end.

You see this requires slightly more code, but it is still a very small program. Well, now we go to the last example, which downloads any file and saves it to disk. You can use it as a template for your own code, it demonstrates almost everything you need.

program dl_fphttp_d;

{$mode delphi}{$ifdef windows}{$apptype console}{$endif}

uses
sysutils,
classes,
fphttpclient,
fpopenssl,
openssl;

const
Filename = 'testdownload.txt';

var
Client: TFPHttpClient;
FS: TStream;
SL: TStringList;

begin

{ SSL initialization has to be done by hand here }
InitSSLInterface;

Client := TFPHttpClient.Create(nil);
FS := TFileStream.Create(Filename,fmCreate or fmOpenWrite);
try
try
{ Allow redirections }
Client.AllowRedirect := true;
Client.Get('https://google.com/',FS);
except
on E: EHttpClient do
writeln(E.Message)
else
raise;
end;
finally
FS.Free;
Client.Free;
end;

{ Test our file }
if FileExists(Filename) then
try
SL := TStringList.Create;
SL.LoadFromFile(Filename);
writeln(SL.Text);
finally
SL.Free;
end;
end.

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.

Form data and encoding

FormPost(const URL: string; FormData: TStrings; const Response: TStream);

FormPost(const URL, FormData: string; const Response: TStream);

If you pass FormData as TStrings the FormPost procedure performs EncodeURLElement but if you pass FormData as simple string to FormPost, then EncodeURLElement is not performed.

There is no difference in the behaviour if the data in FormData does not need to be encoded, but there is different behaviour for strings which include characters which are not allowed (eg '@', '=', etc).
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:
{
Current IP CheckCurrent IP Address: 44.151.191.44
}
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
External links

fpHTTPClient Tutorial.


总数:0 页次:1/0 首页 尾页  
总数:0 页次:1/0 首页 尾页  


所在合集/目录



发表评论:
文本/html模式切换 插入图片 文本/html模式切换


附件:



NEWBT官方QQ群1: 276678893
可求档连环画,漫画;询问文本处理大师等软件使用技巧;求档softhub软件下载及使用技巧.
但不可"开车",严禁国家敏感话题,不可求档涉及版权的文档软件.
验证问题说明申请入群原因即可.

Copyright © 2005-2020 clq, All Rights Reserved
版权所有
桂ICP备15002303号-1