Einzelnen Beitrag anzeigen

mjustin

Registriert seit: 14. Apr 2008
3.005 Beiträge
 
Delphi 2009 Professional
 
#1

POST mit TIdHTTP: Codebeispiel mit HTTPS

  Alt 22. Feb 2015, 08:13
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
Michael Justin
habarisoft.com

Geändert von mjustin (22. Feb 2015 um 08:17 Uhr) Grund: Tippfehler in Überschrift
  Mit Zitat antworten Zitat