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.

program JSONPostExample;

{$APPTYPE CONSOLE}

uses
  IdHTTP, IdGlobal, SysUtils, Classes;

var
  HTTP: TIdHTTP;
  RequestBody: TStream;
  ResponseBody: string;
begin
  HTTP := TIdHTTP.Create;
  try
    try
      RequestBody := TStringStream.Create('{"日本語":42}',
        TEncoding.UTF8);
      try
        HTTP.Request.Accept := 'application/json';
        HTTP.Request.ContentType := 'application/json';
        ResponseBody := HTTP.Post('https://httpbin.org/post',
          RequestBody);
        WriteLn(ResponseBody);
        WriteLn(HTTP.ResponseText);
      finally
        RequestBody.Free;
      end;
    except
      on E: EIdHTTPProtocolException do
      begin
        WriteLn(E.Message);
        WriteLn(E.ErrorMessage);
      end;
      on E: Exception do
      begin
        WriteLn(E.Message);
      end;
    end;
  finally
    HTTP.Free;
  end;
  ReadLn;
  ReportMemoryLeaksOnShutdown := True;
end.

Notes:

  • line 16: 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.
  • line 17: make sure you encode the JSON body as UTF-8
  • line 21: Indy will create a SSLIOHander for a URL beginning with https

Program output:

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

HTTP/1.1 200 OK
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s