Answer the question
In order to leave comments, you need to log in
How to send WinSock requests (GET, POST)?
Hello, I still can’t figure out how to send requests to the site via WinSock. As far as I understand, the problem is in the code. Tell me what's wrong
function wpost(host, URL, data: string): string;
var
req{,data} : string;
buf : array[0..1500] of char;
wData : WSADATA;
addr : sockaddr_in;
sock : integer;
error : integer;
phe : PHostEnt;
begin
Result := '';
WSAStartup($0101, wData);
phe := gethostbyname(PChar(string(host)));
if phe = nil then begin
WSACleanup;
exit;
end;
sock := socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if sock = INVALID_SOCKET then begin
WSACleanup;
exit;
end;
addr.sin_family := AF_INET;
addr.sin_port := htons(80);
addr.sin_addr := PInAddr(phe.h_addr_list^)^;
error := connect(sock, addr, sizeof(addr));
if error = SOCKET_ERROR then begin
closesocket(sock);
WSACleanup;
exit;
end;
req :='POST '+URL+' HTTP/1.1'#13#10+
'Host: '+host+#13#10+
'User-Agent: Opera/9.24 (Windows NT 5.1; U; en)'#13#10+
'Content-Length: '+inttostr(length(data))+#13#10+
'Content-Type: application/x-www-form-urlencoded'#13#10#13#10+data;
if Send(Sock,pointer(req)^,length(req),0)=SOCKET_ERROR then exit;
fillchar(buf,sizeof(buf),0);
recv(Sock,buf,sizeof(buf),0);//sizeof(buf
closesocket(Sock);
result:=buf;
end;
function wget(host,param:string):string;
var
info: WSADATA;
sin: sockaddr_in;
sHwnd: integer;
sBuff1:string;
sBuff, rBuff: array [0..99999] of char;
phe : PHostEnt;
begin
WSAStartup(makeword(1,1),info);
phe := gethostbyname(PChar(string(host)));
sHwnd :=0;
try
sHwnd :=Socket(AF_INET, SOCK_STREAM, 0);
IF sHwnd = INVALID_SOCKET then begin WSACleanup; exit; end;
sin.sin_family:=AF_INET;
sin.sin_port:=htons(80);
sin.sin_addr := PInAddr(phe.h_addr_list^)^;
connect(sHwnd, sin, sizeof(sin));
sbuff1:='GET '+param+' HTTP/1.1' + #13#10 +
'Host: '+host+ #13#10 +
#13#10;
CopyMemory(@sBuff,pchar(sBuff1),length(sBuff1));
send(sHwnd, sBuff, Length(sBuff), 0);
recv(sHwnd, rBuff, Length(rBuff), 0);
finally
Result :=rBuff;
Closesocket(sHwnd);
WSACleanup;
end;
end;
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question