Delphi-PRAXiS

Delphi-PRAXiS (https://www.delphipraxis.net/forum.php)
-   Netzwerke (https://www.delphipraxis.net/14-netzwerke/)
-   -   POST mit TIdHTTP: Codebeispiel mit HTTPS (https://www.delphipraxis.net/184056-post-mit-tidhttp-codebeispiel-mit-https.html)

mjustin 22. Feb 2015 08:13


POST mit TIdHTTP: Codebeispiel mit HTTPS
 
Da es beim HTTP POST mit Indy einige Stolpersteine gibt, hier ein Beispiel. Es sendet einen Request über HTTPS (dazu sind die OpenSSL DLLs im Programmverzeichnis erforderlich), dessen Inhalt ein JSON Objekt (UTF-8 kodiert) ist. Das Programm zeigt dann die Antwort des Testservers an.

Delphi-Quellcode:
program JSONPostExample;

{$APPTYPE CONSOLE}

uses
  IdHTTP, SysUtils, Classes, IdGlobal;

var
  HTTP: TIdHTTP;
  RequestBody: TStringStream;
begin
  HTTP := TIdHTTP.Create;
  try
    try
      RequestBody := TStringStream.Create('{"日本語":42}', TEncoding.UTF8);
      try
        WriteLn(HTTP.Post('https://httpbin.org/post', RequestBody));
        WriteLn(HTTP.ResponseText);
      finally
        RequestBody.Free;
      end;
    except
      on E: EIdHTTPProtocolException do
      begin
        WriteLn(E.Message + #13#10#13#10 + E.ErrorMessage);
      end;
      on E: Exception do
      begin
        WriteLn(E.Message);
      end;
    end;
  finally
    HTTP.Free;
  end;
  ReadLn;
  ReportMemoryLeaksOnShutdown := True;
end.
Serverantwort:

Code:
{
  "args": {},
  "data": "{\"\u65e5\u672c\u8a9e\":42}",
  "files": {},
  "form": {},
  "headers": {
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",

    "Accept-Encoding": "identity",
    "Content-Length": "16",
    "Host": "httpbin.org",
    "User-Agent": "Mozilla/3.0 (compatible; Indy Library)"
  },
  "json": {
    "\u65e5\u672c\u8a9e": 42
  },
  "origin": "80.137.6.116",
  "url": "https://httpbin.org/post"
}

HTTP/1.1 200 OK
Getestet mit Delphi 2009 und Indy 10.6.2


Alle Zeitangaben in WEZ +1. Es ist jetzt 04:20 Uhr.

Powered by vBulletin® Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
LinkBacks Enabled by vBSEO © 2011, Crawlability, Inc.
Delphi-PRAXiS (c) 2002 - 2023 by Daniel R. Wolf, 2024 by Thomas Breitkreuz