Skip to content

Instantly share code, notes, and snippets.

@SevanBadal
Created November 12, 2022 21:37
Show Gist options
  • Save SevanBadal/545fd89bdf1a7d1461fe4ef9f7680551 to your computer and use it in GitHub Desktop.
Save SevanBadal/545fd89bdf1a7d1461fe4ef9f7680551 to your computer and use it in GitHub Desktop.
HTTP POST example using Ada's GNAT Sockets library
with GNAT.Sockets;
with Ada.Text_IO;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Streams; use Ada.Streams;
procedure Ada_Http_Post is
CRLF : constant String := ASCII.CR & ASCII.LF;
Host : constant String := "httpbin.org";
Path : constant String := "/post";
Host_Entry : constant GNAT.Sockets.Host_Entry_Type :=
GNAT.Sockets.Get_Host_By_Name (Host);
Address : GNAT.Sockets.Sock_Addr_Type;
Socket : GNAT.Sockets.Socket_Type;
Channel : GNAT.Sockets.Stream_Access;
Data : Ada.Streams.Stream_Element_Array (1 .. 1024);
Size : Ada.Streams.Stream_Element_Offset;
Response_String : Ada.Strings.Unbounded.Unbounded_String;
begin
Address.Addr := GNAT.Sockets.Addresses (Host_Entry, 1);
Address.Port := 80;
GNAT.Sockets.Create_Socket (Socket);
GNAT.Sockets.Connect_Socket (Socket, Address);
Channel := GNAT.Sockets.Stream (Socket);
String'Write (Channel, "POST " & Path & " HTTP/1.1" & CRLF &
"HOST: " & Host & CRLF &
"Content-Type: text/plain" & CRLF &
"Content-Length: 12" & CRLF & CRLF &
"query_string"
);
GNAT.Sockets.Receive_Socket (Socket, Data, Size);
for i in 1 .. Size loop
Response_String := Response_String & Character'Val (Data (i));
end loop;
Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Response_String));
end Ada_Http_Post;
@SevanBadal
Copy link
Author

Prints:

HTTP/1.1 200 OK
Date: Sat, 12 Nov 2022 21:37:35 GMT
Content-Type: application/json
Content-Length: 339
Connection: keep-alive
Server: gunicorn/19.9.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true

{
  "args": {}, 
  "data": "query_string", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Content-Length": "12", 
    "Content-Type": "text/plain", 
    "Host": "httpbin.org", 
    "X-Amzn-Trace-Id": "Root=1-xxxxx-xxxxx"
  }, 
  "json": null, 
  "origin": "xxx.xxx.xx.xxx", 
  "url": "http://httpbin.org/post"
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment