delphi IdHTTP post 支持 gzip 解压缩


本文整理自网络,侵删。

 
unit Unit3;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IdBaseComponent, IdZLibCompressorBase,
  IdCompressorZLib, Vcl.StdCtrls;

type
  TForm3 = class(TForm)
    IdCompressorZLib1: TIdCompressorZLib;
    Memo1: TMemo;
    Button1: TButton;
    Memo2: TMemo;
    procedure Button1Click(Sender: TObject);

  private

    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form3: TForm3;

implementation

{$R *.dfm}


uses IdHTTP;

function post_http(const url: string; t: tstringlist): string;
var memstr,outstr: TStringStream;
    idhttp1: Tidhttp;
    j: integer;
    label pp;
begin
 j:= 0;
 //screen.Cursor:= crhourglass;
  memstr:= TStringStream.Create('',TEncoding.UTF8);

   pp:
   idhttp1:= Tidhttp.Create(nil);
   IdHTTP1.HTTPOptions := IdHTTP1.HTTPOptions + [hoKeepOrigProtocol]; //必须有这行才使设置协议版本生效
   IdHTTP1.ProtocolVersion := pv1_1;
   idhttp1.HandleRedirects:=True;
   IdHTTP1.Request.AcceptEncoding :='gzip';
   idhttp1.ReadTimeout:= 30000;
   idhttp1.ConnectTimeout := 10000;
   //idhttp1.AllowCookies:= false;
     try
      if t=nil then
      IdHTTP1.get(url,memstr)
      else
      IdHTTP1.Post(url,t,memstr);
     except
        if j=0 then
        j:= 1
        else begin
               result:= 'neterror';
                memstr.Free;
                idhttp1.Free;
                //screen.Cursor:= crdefault;
               exit;
             end;
     end;

        if j=1 then
        begin
          j:= 2;
          idhttp1.Free;
          sleep(2000);
          goto pp; //网络错误时重试一次
        end;

      if IdHTTP1.Response.ContentEncoding = 'gzip' then
       begin
         outstr:= TStringStream.Create('',TEncoding.UTF8);
         if memstr.Size=0 then
           result:='返回数据为空'
           else begin
         memstr.Position:= 0;
         form3.IdCompressorZLib1.DecompressGZipStream(memstr, outstr);
         outstr.Position := 0;
         result:= outstr.DataString;
         //memo1.Lines.Add('压缩前'+inttostr(outstr.Size));
         //memo1.Lines.Add('压缩后'+inttostr(memstr.Size));
                end;
         outstr.Free;
       end else begin
         result:= memstr.DataString;
       end;
   idhttp1.Free;
  //screen.Cursor:= crdefault;

  memstr.Free;

end;


procedure TForm3.Button1Click(Sender: TObject);
var
tt:tstringlist;
begin
tt:=tstringlist.Create;

memo1.Text:=post_http('http://www.cha128.com/api/DayEnglish/',nil);
end;

end.

相关阅读 >>

Delphi 安卓 app 动态权限申请

Delphi idhttp 获取链接连通状态

minsperday:一天中有多少分钟

Delphi保存网页中的图片

Delphi 显示提示信息xxx 是/否

Delphi 将base64字符串转化为jpeg图片

Delphi xe8在firemonkey tlistbox中显示图像

Delphi 读文件到十六进制的函数(Delphi 7 下可用)

Delphi窗体显示echarts图表

Delphi 守护进程 杀死自己的进程再重新启动自己

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...