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.
Notes:
- 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.
- 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
- {
- "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
No comments:
Post a Comment