怎样直接用winsock获取指定网页内容(类似HTTP控件的GET或POST获取网页内容功能)最好给段例子(200分)

  • 主题发起人 主题发起人 hmf9
  • 开始时间 开始时间
H

hmf9

Unregistered / Unconfirmed
GUEST, unregistred user!
怎样直接用winsock获取指定网页内容(类似HTTP控件的GET或POST获取网页内容功能)最好给段例子

 
呵呵,给你一个用indy TCPClient的例子。
c 是TIdTCPClient, Host设为HTTP Server主机,端口80
procedure TForm1.Button1Click(Sender: TObject);
var
S: String;
Len: Integer;
begin
c.Connect;
c.writeln('GET / HTTP/1.1');
c.writeln('Content-Type: text/html');
c.writeln('Host: www.delphibbs.com');
c.writeln('Accept: text/html,*/*');
c.writeln('User-Agent: Mozilla/3.0 (compatible; Indy Library)');
c.writeln('');
Len := 0;
repeat
s := c.readln;
if Copy(S, 1, 14) = 'Content-Length' then
Len := StrToInt(Copy(S, 16, MAXINT));
until s = '';
S := c.ReadString(Len);
memo1.lines.text := s;
end;
 
我要完全用WINSOCK写的,不要VCL的。
 
完全用WINSOCK写的,以http://www.21cn.com/为例:

var
len,s:integer;
name:sockaddr_in;
he:PHostEnt;
buf:array[0..1023]of char;
str,data:string;
wsd:WSADATA;
begin
WSAStartup($101,wsd);
s:=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
he:=gethostbyname('www.21cn.com');
if he=nil then
Raise Exception.Create('err');

FillChar(name,sizeof(name),0);
name.sin_family:=AF_INET;
name.sin_port:=htons(80);
name.sin_addr.S_addr:=PDWORD(PDWORD(he.h_addr)^)^;
connect(s,name,sizeof(name));

str:='GET / HTTP/1.1'#13#10'Host: www.21cn.com'#13#10'Connection: Close'#13#10#13#10;
send(s,PChar(str)^,Length(str),0);
while true do
begin
len:=recv(s,buf,sizeof(buf),0);
if len<1 then
break;
SetString(str,buf,len);
data:=data+str;
end;
closesocket(s);
WSACleanup();
ShowMessage(data);
end;
 
bt.cnxp.com这样的网站两种方法都不能成功!help!
 
后退
顶部