获取网页信息另一种方式

时间:2010-02-01 13:19:04  来源:第二电脑网  作者:第二电脑网

  第二电脑网导读:ton;TcpClient1: TTcpClient;Memo1: TMemo;Edit1: TEdit;procedure Button1Click(Sender: TObject);private{ Private declarations }public{ Public declarations }end;varForm1: TForm1;implementation{$R *.dfm}procedure TForm1.Button1Click(Sen...
  正文:unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Sockets;

type
TForm1 = class(TForm)
Button1: TButton;
TcpClient1: TTcpClient;
Memo1: TMemo;
Edit1: TEdit;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
Test: string;
HttpLen: integer;
begin
  TcpClient1.RemoteHost := 'www.163.cn';
  TcpClient1.RemotePort := '80';
  TcpClient1.Active := true;
  if TcpClient1.Connected then
  begin
    //发送HTTP1.1指令
TcpClient1.Sendln('GET / HTTP/1.1');
    TcpClient1.Sendln('Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/msword, */*');
    TcpClient1.Sendln('User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; Maxthon)');
    TcpClient1.Sendln('Host: www.163.cn');
    TcpClient1.Sendln('Connection: Keep-Alive');
    TcpClient1.Sendln('');
  end;
  HttpLen := 0;
  //循环读取所有返回的数据头信息
while true do
  begin
    Test := TcpClient1.Receiveln();
    Memo1.Lines.Add(Test);
    if Test = '' then Break;
    if Pos('Content-Length: ', Test) > 0 then
    begin
      Delete(Test, 1, 16);
      HttpLen := StrToInt(Test); //获取将要读取的数据长度
end;
  end;
  LockWindowUpdate(Memo1.Handle);
  Memo1.Clear;
  //循环读取所有返回的数据直接数据接收完毕
while (Length(Memo1.Text) < HttpLen - 2) or (TcpClient1.WaitForData(0) and (HttpLen = 0)) do
  begin
    Memo1.Lines.Add(TcpClient1.Receiveln(#$0D#$0A));
    Application.ProcessMessages;
    Edit1.Text := Format('总长度:%d 已下载:%d ', [HttpLen, Length(Memo1.Text)]);
  end;
  
  //有些网页返回的非ANSI字符串,则需要转码,否则中文全是乱码
if Length(Memo1.Text) = HttpLen - 2 then Memo1.Text := Utf8ToAnsi(Memo1.Text);
  
  LockWindowUpdate(0);
  Memo1.Lines.SaveToFile('d:test.txt');
  ShowMessage('完成数据下载');
end;

end. 《获取网页信息另一种方式》由第二电脑网原创提供,转载请注明:http://www.002pc.com/master/College/Language/Delphi/12723.html


关键字:

关于《获取网页信息另一种方式》文章的评论

站内搜索: 高级搜索

热门搜索: Windows style 系统 tr IP QQ CPU 安装 function 注册 if td