' Cheapie http file snatcher for Rapid-Q (Windows) by William Yu
' Fixed a header problem, sorry about that, should work for all webpages now.
' Your program might hang (ie. block a few minutes) if it can't locate the
' http server.

$APPTYPE GUI
$TYPECHECK ON
$INCLUDE "rapidq.inc"

DECLARE SUB ButtonClick

CONST PortNum = 80        '' Standard HTTP port.

DIM Socket AS QSOCKET
DIM Sock AS INTEGER

CREATE Form AS QForm
  Width = 400
  Height = 400
  Center
  Caption = "Cheapie http file snatcher"
  CREATE URLLabel AS QLabel
    Left = 8
    Top = 12
    Caption = "URL: "
  END CREATE
  CREATE Edit AS QEdit
    Left = 45
    Top = 8
    Width = 230
    Text = "http://www.yahoo.com/"
  END CREATE
  CREATE Button AS QButton
    Left = 300
    Top = 6
    Caption = "&Get it!"
    OnClick = ButtonClick
  END CREATE
  CREATE RichEdit AS QRichEdit
    Top = 45
    Width = Form.ClientWidth
    Height = 307
    PlainText = True
    WordWrap = False
    ScrollBars = ssBoth
  END CREATE
  ShowModal
END CREATE


SUB ButtonClick
  DIM Text AS STRING
  DIM Bytes AS LONG
  DIM Server AS STRING, PathToFile AS STRING
  DIM I AS INTEGER

  PathToFile = ""
  Server = Edit.Text - "http://"       '' Take out http://

  I = INSTR(Server, "/")
  IF I THEN
    PathToFile = MID$(Server, I, LEN(Server)+1-I)
    Server = LEFT$(Server, I-1)
  END IF

  Sock = Socket.Connect(Server, PortNum)
    ShowMessage(Socket.GetPeerName(Sock))


  IF Sock < 0 THEN
    ShowMessage "Could not make connection"
    EXIT SUB
  END IF

  '-- Send request, end with a blank line.
  Socket.WriteLine(Sock, "GET "+PathToFile+" HTTP/1.0")
  '-- This line is optional...
  Socket.WriteLine(Sock, "HOST "+Server+":"+STR$(PortNum))

  Socket.WriteLine(Sock, "")    '-- End request

  Text = ""
  Bytes = 0
  '-- Might not actually retrieve the whole file...
  DO
    Text = Text + Socket.Read(Sock, 32000)     '' 32000 bytes... whatever they give us
    Bytes = Bytes + Socket.Transferred
  LOOP UNTIL Socket.Transferred = 0
  RichEdit.Clear
  RichEdit.Text = Text
  Socket.Close
END SUB
