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开发的服务中调用指定应用程序

Delphi 如何确定活动桌面是否已启用

Delphi操作usb摄像头类

Delphi xe5 android程序常用的unit

Delphi调节图片亮度、色彩和饱和度的代码

Delphi中使用tlist类的简单分析

Delphi中的处理事件 application.processmessages

Delphi定位注册表指定键位

Delphi 通用压缩单元

Delphi memo1文本搜索并高亮

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



打赏

取消

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

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

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

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

评论

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