您现在的位置:首页 >> 网络通讯 >> 网络通讯 >> 内容

Delphi的WinSocket封装HTTP请求代码示例

时间:2011/9/3 15:14:25 点击:

  核心提示:procedure TForm1.Button2Click(Sender: TObject); function InitSocket: TSocket; var m_wsData: TWSAData...
procedure TForm1.Button2Click(Sender: TObject);
  function InitSocket: TSocket;
  var
    m_wsData: TWSAData;
  begin
    WSAStartUp(MAKEWORD(2, 2), m_wsData);

    Result:= Socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  end;
  function FormatHead(Method, SvrIP: string; strURL: string; SvrPort: integer): string;
  begin
    Result:= Method + ' /'+ strURL +' HTTP/1.1'#13#10;    //Get Head
    Result:= Result + 'Referer: http://' + SvrIP;

    if SvrPort <> 80 then
      Result:= Result + ':' + IntToStr(SvrPort);

    Result:= Result + '/' + strURL + #13#10;
    Result:= Result + 'User-Agent: Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)'#13#10;
    Result:= Result + 'Host: ' + SvrIP;

    if SvrPort <> 80 then
      Result:= Result + ':' + IntToStr(SvrPort);

    Result:= Result + #13#10;
    Result:= Result + 'Accept: */*'#13#10;
    Result:= Result + 'Connection: Close'#13#10;
    Result:= Result + 'Cache-Control: no-cache'#13#10;

    Result:= Result + #13#10;
  end;
var
  addr  : sockaddr_in;
  pHost : pHostEnt;
  Sock: TSocket;
  strTmp:string;
  strBuf: array[0..1023] of Char;
  intLen: integer;
begin
  Sock:= InitSocket;
  if Sock = INVALID_SOCKET then Exit;

  pHost:= GetHostByName(PChar('beijing.baixing.com'));
  if pHost = nil  then Exit;
  FillChar(addr, SizeOf(addr), 0);
  addr.sin_family:= AF_INET;
  addr.sin_Port  := htons(80);
  addr.sin_addr.S_addr:= PDWORD(PDWORD(pHost.h_addr)^)^;
  if Connect(Sock, addr, SizeOf(addr)) = SOCKET_ERROR then
  begin
    ShowMessage('Socket Error:' + IntToStr(WSAGetLastError));
    Exit;
  end;
  strTmp:= FormatHead('GET', 'beijing.baixing.com', '/girlfriend/a31378556.html', 80);
  Send(Sock, PChar(strTmp)^, Length(strTmp), 0);
  strTmp:='';
  while True do
  begin
    FillChar(strBuf, 1024, #0);
    intLen:= Recv(Sock, strBuf, 1024, 0);
    SetString(strTmp, strBuf, 1023);
    Memo1.Lines.Add(UTF8Decode(strTmp));
    if intLen < 1 then Break;
  end;
  CloseSocket(Sock);
  WSACleanUp();
end;

作者:网络 来源:转载
共有评论 0相关评论
发表我的评论
  • 大名:
  • 内容:
  • 盒子文章(www.2ccc.com) © 2022 版权所有 All Rights Reserved.
  • 沪ICP备05001939号