首页  编辑  

使用WININET直接获取页面内容

Tags: /超级猛料/Web.互联网开发技术/   Date Created:

使用WININET直接获取页面内容

function HttpRequestExecute(const URL, QureyData: string): string;

var

  hSession, hConnect, hRequest: hInternet;

  RequestMethod, TempStr, HostName, FileName: string;

  BytesToRead      : cardinal;

  DataLength       : integer;

  AData            : array[0..40960] of char;

  InternetFlag     : LongWord;

  AcceptType       : PAnsiChar;

  Buf              : array[0..1023] of char;

  dwBufLen, dwIndex: LongWord;

  procedure ParseURL(URL: string; var HostName, FileName: string);

  var

     i             : Integer;

  begin

     if Pos('http://', URL) <> 0 then

        System.Delete(URL, 1, 7);

     i := Pos('/', URL);

     HostName := Copy(URL, 1, i);

     FileName := Copy(URL, i, Length(URL) - i + 1);

     if (Length(HostName) > 0) and (HostName[Length(HostName)] = '/') then

        SetLength(HostName, Length(HostName) - 1);

  end;

  procedure CloseHandles;

  begin

     InternetCloseHandle(hRequest);

     InternetCloseHandle(hConnect);

     InternetCloseHandle(hSession);

  end;

begin

  result := '';

  ParseURL(URL, HostName, FileName);

  hSession := InternetOpen(PChar(''),

     INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);

  hConnect := InternetConnect(hSession, PChar(HostName),

     INTERNET_DEFAULT_HTTP_PORT, '', '', INTERNET_SERVICE_HTTP, 0, 0);

  if QureyData = '' then RequestMethod := 'GET'

  else RequestMethod := 'POST';

  InternetFlag := 0;

  AcceptType := PChar('Accept: */*');

  hRequest := HttpOpenRequest(hConnect, PChar(RequestMethod), PChar(FileName), 'HTTP/1.0',

     '', @AcceptType, InternetFlag, 0);

  if QureyData = '' then

     HttpSendRequest(hRequest, nil, 0, nil, 0)

  else

     HttpSendRequest(hRequest, 'Content-Type: application/x-www-form-urlencoded', 47,

        PChar(QureyData), Length(QureyData));

  BytesToRead := 0;

  dwIndex := 0;

  dwBufLen := sizeof(Buf);

  HttpQueryInfo(hRequest, HTTP_QUERY_CONTENT_LENGTH, @Buf, dwBufLen, dwIndex);

  DataLength := StrToIntDef(Buf, 0);

  while InternetReadFile(hRequest, @AData, SizeOf(AData), BytesToRead) do

  begin

     if BytesToRead = 0 then break;

     SetString(TempStr, AData, BytesToRead);

     Result := Result + TempStr;

  end;

  CloseHandles;

end;

使用时:

memo2.Lines.Text :=HttpRequestExecute(edit1.Text ,'') ;