' iBHttpGet.ibas
{CREATORID "LDIH"}
{VERSION "1.0"}
{PARSER ON}


'----------------------------------
' Method #1 - Standard Network 
' statements use
' Note how to build a HTTP request
' to a web server which in return
' sends back a HTML web page
'----------------------------------

_Method1:
 L$=CHR$(10)
 M$=CHR$(13)+L$
' Open Network
 GOSUB _URLdomain : D$=S$
 GOSUB _URLport : S$=D$+":"+S$
 OPEN NET S$ AS #1
 A=FILEERROR
 IF A=1 THEN
  A=MESSAGEBOX("Error while opening Net"+L$+"Exiting...",1)
  CLOSE #1
  RETURN
 END IF
' Build HTTP GET request
 S=1
 CLEAR$$
 GOSUB _URLpage
 S$="GET /"+S$
 ADDSTRING$$ S$
 S$=" HTTP/1.1"+M$
 ADDSTRING$$ S$
 S$="Host: "+D$+M$
 ADDSTRING$$ S$
 S$="Connection: close"+M$
 ADDSTRING$$ S$
 S$="User-Agent: iziBasic/Palm v"
 V=VERSION
 S$=S$+STR$(V,1)+M$+M$
 ADDSTRING$$ S$
' Send HTTP request
 PRINT$$ #1
 A=FILEERROR
 IF A=1 THEN
  A=MESSAGEBOX("Error while sending HTTP request",1)
 END IF
' Receive HTTP answer
 INPUT$$ #1
 A=FILEERROR
 IF A=1 THEN
  A=MESSAGEBOX("Error while receiving HTTP answer",1)
 END IF
' Close Network
 CLOSE #1
 A=FILEERROR
 IF A=1 THEN
  A=MESSAGEBOX("Error while closing Net",1)
 END IF
RETURN

_URLdomain:
 S$="" : N=1 : L=LEN(P$)
 WHILE N<=L
  A$=CHAR$(P$,N)
  A=FALSE
  IF A$<>"/" IF A$<>":" LET A=TRUE
  IF A=TRUE THEN
    S$=S$+A$ : INC N
  ELSE
   N=L+1
  ENDIF
 WEND
RETURN

_URLpage:
 S$="" : L=LEN(P$) : I=1 : J=L
 FOR N=1 TO L
  A$=CHAR$(P$,N)
  IF A$="/" IF I=1 LET I=N+1
  IF A$=":" IF J=L LET J=N-1
 NEXT
 IF I>1 LET J=J-I+1 : S$=MID$(P$,I,J)
RETURN

_URLport:
 S$="" : N=1 : L=LEN(P$)
 WHILE N<L
  A$=CHAR$(P$,N)
  INC N
  IF A$=":" LET S$=MID$(P$,N,L) : N=L
 WEND
 N=VAL(S$) : N=INT(N)
 IF N=0 LET N=80 ' default HTTP port
 S$=STR$(N,0)
RETURN


'----------------------------------
' Method #2 - Same result as in
' Method #1 but in one single 
' iziBasic statement!
'----------------------------------

_Method2:
 HTTPGET$$ P$
 A=FILEERROR
 IF A=1 THEN
  A$="Error while retrieving HTTP request & answer"
  A=MESSAGEBOX(A$,1)
 END IF
RETURN


'----------------------------------
' Main Program
'----------------------------------

_RemoveHTTP:
 A$=LEFT$(P$,7) : A$=LCASE$(A$)
 IF A$="http://" LET P$=MID$(P$,8,63)
RETURN

BEGIN
 P$="izibasic.aldweb.com" 
 LABEL #1,"URL:",5,19
 TEXTFIELD #2,P$,0,30,18,125,11
 BUTTON #3,"Get Method #1",7,35,70,12
 BUTTON #4,"Get Method #2",83,35,70,12
 TEXTFIELD$$ #5,4096,5,55,140,100
 SCROLLBAR #6,1,150,55,9,104
 REPEAT
  E=WAITEVENT
  SELECT CASE E
   CASE 3
    P$=FIELD$(#2)
    GOSUB _RemoveHTTP
    GOSUB _Method1
    TEXTFIELD$$ #5,4096,5,55,140,100
   CASE 4
    P$=FIELD$(#2)
    GOSUB _RemoveHTTP
    GOSUB _Method2
    TEXTFIELD$$ #5,4096,5,55,140,100
   CASE 6
    A=SCROLLBAR(#6)
    FIELDPOS #5,A
  END SELECT
 UNTIL E=-1
END
