This question already has an answer here:
I want to send a HTTP Post Request in Delphi 2010 using WinInet, but my script doesn't work ;/
It's my Delphi script:
uses WinInet;
procedure TForm1.Button1Click(Sender: TObject);
var
hNet,hURL,hRequest: HINTERNET;
begin
hNet := InternetOpen(PChar('User Agent'),INTERNET_OPEN_TYPE_PRECONFIG or INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
if Assigned(hNet) then
begin
try
hURL := InternetConnect(hNet,PChar('http://localhost/delphitest.php'),INTERNET_DEFAULT_HTTP_PORT,nil,nil,INTERNET_SERVICE_HTTP,0,DWORD(0));
if(hURL<>nil) then
hRequest := HttpOpenRequest(hURL, 'POST', PChar('test=test'),'HTTP/1.0',PChar(''), nil, INTERNET_FLAG_RELOAD or INTERNET_FLAG_PRAGMA_NOCACHE,0);
if(hRequest<>nil) then
HttpSendRequest(hRequest, nil, 0, nil, 0);
InternetCloseHandle(hNet);
except
ShowMessage('error');
end
end;
end;
and my PHP script:
$data = $_POST['test'];
$file = "test.txt";
$fp = fopen($file, "a");
flock($fp, 2);
fwrite($fp, $data);
flock($fp, 3);
fclose($fp);
Major problems:
The second parameter of
InternetConnect
should contain only the name of the server, not the entire URL of the server-side script.The third parameter of
HttpOpenRequest
should be the file name (URL) of the script, not the POST data!The actual POST data should be the forth parameter of
HttpSendRequest
.Minor problems
INTERNET_OPEN_TYPE_PRECONFIG or INTERNET_OPEN_TYPE_PRECONFIG
: It is sufficient withINTERNET_OPEN_TYPE_PRECONFIG
.DWORD(0)
is overkill.0
is enough.Sample Code
I use the following code to POST data:
For instance:
Update in response to answer by OP
To read data from the Internet, use
InternetReadFile
function. I use the following code to read a small (one-line) text file from the Internet:Sample usage:
This function thus only reads data, with no prior POST. However, the
InternetReadFile
function can also be used with a handle created byHttpOpenRequest
, so it will work in your case also. You do know that the WinInet reference is MSDN, right? All Windows API functions are described in detail there, for instance InternetReadFile.There is a library (called 'HTTPGet component for Delphi 32') on http://www.utilmind.com. It installs a visual control into your component palette. It does exactly what you want, so you may want to take a look.