Friday, January 19, 2018

idHTTP Sample code delphi XE



Indy 10.6 HTTPS POST example with JSON body


The Indy (Internet Direct) TIdHTTP now creates a default SSLIOHandler when requesting an HTTPS url. This makes TIdHTTP a little easier to use “out of the box”. (blog article).

The code below sends a hard-coded JSON object as POST body to a secure url. Note: if you need to customize the SSLVersions used, or specify certificates/keys, or use status/password event handlers, then you will still have to explicitly assign an SSLIOHandler component to the TIdHTTP.IOHandler property before sending an HTTPS request.


  1. uses
  2.   IdHTTP, IdGlobal, SysUtils, Classes;
  3.  
  4. var
  5.   HTTP: TIdHTTP;
  6.   RequestBody: TStream;
  7.   ResponseBody: string;
  8. begin
  9.   HTTP := TIdHTTP.Create;
  10.   try
  11.     try
  12.       RequestBody := TStringStream.Create('{"日本語":42}',
  13.         TEncoding.UTF8);
  14.       try
  15.         HTTP.Request.Accept := 'application/json';
  16.         HTTP.Request.ContentType := 'application/json';
  17.         ResponseBody := HTTP.Post('https://httpbin.org/post',
  18.           RequestBody);
  19.         WriteLn(ResponseBody);
  20.         WriteLn(HTTP.ResponseText);
  21.       finally
  22.         RequestBody.Free;
  23.       end;
  24.     except
  25.       on E: EIdHTTPProtocolException do
  26.       begin
  27.         WriteLn(E.Message);
  28.         WriteLn(E.ErrorMessage);
  29.       end;
  30.       on E: Exception do
  31.       begin
  32.         WriteLn(E.Message);
  33.       end;
  34.     end;
  35.   finally
  36.     HTTP.Free;
  37.   end;
  38.   ReadLn;
  39.   ReportMemoryLeaksOnShutdown := True;
  40. end.
Notes:


  • you must not use a TStringList for the POST body. That version of TIdHTTP.Post() formats the data according to the application/x-www-form-urlencoded media type, which is not appropriate for JSON and will corrupt it.
  • make sure you encode the JSON body as UTF-8
  • Indy will create a SSLIOHander for a URL beginning with https




  1. {
  2.   "args": {},
  3.   "data": "{\"\u65e5\u672c\u8a9e\":42}",
  4.   "files": {},
  5.   "form": {},
  6.   "headers": {
  7.     "Accept": "application/json",
  8.     "Accept-Encoding": "identity",
  9.     "Content-Length": "16",
  10.     "Content-Type": "application/json",
  11.     "Host": "httpbin.org",
  12.     "User-Agent": "Mozilla/3.0 (compatible; Indy Library)"
  13.   },
  14.   "json": {
  15.     "\u65e5\u672c\u8a9e": 42
  16.   },
  17.   "origin": "*.*.*.*",
  18.   "url": "https://httpbin.org/post"
  19. }
  20.  
  21. HTTP/1.1 200 OK




No comments:

Post a Comment