本文整理自网络,侵删。
开篇:公司之前一直使用http协议进行交互(比如登录等功能),但是经常被爆安全性不高,所以准备改用https协议。百度了一下资料,其实使用IdHttp控件实现https交互的帖子并不少,鉴于这次成功实现了功能,在此总结分享给大家。开发环境:XE2 + Indy10https服务协议:使用Json格式交互参数Delphi控件:TIdhttp,IdSSLIOHandlerSocketOpenSSL(原生控件)关键DLL:libeay32.dll,ssleay32.dll
为了封装我自己的功能,控件是我自己创建自己释放的,下面列出主要代码。首先,设置Idhttp控件的参数:
FIdHttp := TIdHTTP.Create(nil); IdSSLIOHandlerSocketOpenSSL := TIdSSLIOHandlerSocketOpenSSL.Create(nil); FIdHttp.IOHandler := IdSSLIOHandlerSocketOpenSSL; FIdHttp.HandleRedirects := True; FIdHttp.Request.ContentType := 'application/json';//设置交互方式为json格式 在这里IdSSLIOHandlerSocketOpenSSL.SSLOption.Method为默认值 sslvTLSv1(这个跟需要交互的HTTPS服务有关)。
其次就到交互了:FHttpsURL是需要交互的HTTPS地址,aEnctryPost是需要提交的具体内容,使用流方式提交。aEnctryPost内容举例: {"username":"test","password":"1"}
postStream := TStringStream.Create(aEnctryPost); try postStream.Position := 0; AEnctryRespose := FIdHttp.Post(FHttpsURL, postStream); ShowMessage(AEnctryRespose);//post后的返回内容 finally FIdHttp.Disconnect; FreeAndNil(postStream); end;
常见错误信息: Could not load SSL library:检查libeay32.dll,ssleay32.dll两个DLL的位置(一般放在exe同目录)、版本是否正确。HTTP 1.1 / 415: 检查IdHttp.Request.ContentType := 'application/json' 这里设置的格式是否是要求的格式,有可能是XML格式。
新增代码示例2:unit Unit1;
interface
uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IdTCPConnection, IdTCPClient, IdHTTP, IdBaseComponent, IdComponent, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL, Vcl.StdCtrls;
type TForm1 = class(TForm) IdSSLIOHandlerSocketOpenSSL1: TIdSSLIOHandlerSocketOpenSSL; btnPost: TButton; IdHTTP1: TIdHTTP; procedure FormCreate(Sender: TObject); procedure btnPostClick(Sender: TObject); private { Private declarations } public { Public declarations } end;
var Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.btnPostClick(Sender: TObject);var postStream: TStringStream; AEnctryRespose: string; url: string; aEnctryPost: string;begin url := 'https:/xxx.xx'; aEnctryPost := '{"username":"test","password":"1"}'; postStream := TStringStream.Create(aEnctryPost); try postStream.Position := 0; AEnctryRespose := IdHTTP1.Post(url, postStream); ShowMessage(AEnctryRespose);//post后的返回内容 finally IdHTTP1.Disconnect; FreeAndNil(postStream); end;end;
procedure TForm1.FormCreate(Sender: TObject);begin IdHTTP1 := TIdHTTP.Create(nil); IdSSLIOHandlerSocketOpenSSL1 := TIdSSLIOHandlerSocketOpenSSL.Create(nil); IdHTTP1.IOHandler := IdSSLIOHandlerSocketOpenSSL1; IdHTTP1.HandleRedirects := True; IdHTTP1.Request.ContentType := 'application/json';//设置交互方式为json格式end;
end.
相关阅读 >>
Delphi中转向语句break,continue,exit的作用
Delphi combobox 只读 text属性可用的方法
更多相关阅读请进入《Delphi》频道 >>