[fpc-pascal] Prorammatically sending file using HTTP POST?

Klaus Hartnegg hartnegg at gmx.de
Thu May 3 16:27:17 CEST 2018


Am 04.04.2018 um 13:50 schrieb Bo Berglund:
> By the way, I am using the Indy10 components via the indylaz package.
> Lazarus is 1.8.0 and FPC 3.0.4 on Windows7.

If anybody wants to do this just with winsock:


const
   dstport = 80;
   http_path = '/post.php';

type
   Int32 = Longint;


function wordstr (value:word) : string;
var
   c : string;
begin
   str (value,c);
   wordstr := c;
end;


procedure SendHttpPost (c:ansistring;
                         var msg:string);

var
   wsadata : TWSAData;  // winsock

var
   sock : TSocket;
   addr : sockets.sockaddr_in;
   numbytes : Int32;
   sendstring : ansistring;
   rc : longint;
   ok : boolean;

begin
   // initialize winsock
   if (WSAStartup($0202, wsadata) <> 0) then begin
      msg := 'cannot initialize winsock';
      exit;
   end;

   // get socket
   sock := fpSocket(AF_INET, SOCK_STREAM, 0);
   if (sock = -1) then begin
      msg := 'cannot retrieve socket';
      exit;
   end;


   addr.sin_family := AF_INET;
   addr.sin_port := htons(dstport);
   GetServerIP (addr.sin_addr, ok);

   rc := fpConnect (sock, @addr, sizeof(addr));
   if rc <> 0 then begin
      msg := 'cannot connect to host';
      exit;
   end;

   // c := stringreplace (c,' ','&',[rfReplaceAll]);

   // send data
   sendstring := 'POST '+http_path+' HTTP/1.1'+#13+#10
               + 'host: '+NetAddrToStr(addr.sin_addr)+#13+#10
               + 'Content-Type: application/x-www-form-urlencoded'+#13+#10
               + 'Content-Length: '+wordstr(length(c))+#13+#10
               + #13+#10
               + c;

   numbytes := fpSend(sock, @sendstring[1], length(sendstring), 0);
   if (numbytes = SOCKET_ERROR) then begin
      msg := 'cannot send data to host';
   end else begin
      msg := 'Sent '+wordstr(numbytes)+' bytes to 
'+NetAddrToStr(addr.sin_addr));
   end;

   // clean up
   closesocket(sock);

   // shut down winsock
   WSACleanup;
end;



More information about the fpc-pascal mailing list