; ID: 2208 ; Author: Weijtenburg ; Date: 2008-02-02 05:25:15 ; Title: BlitzThttp object for BlitzMax ; Description: A super fast HTTP object for GET and POST data 'Under HTTP/1.1 all connections are kept alive by default unless stated otherwise with the 'following header: "Connection: close" 'Therefore it is important to use HTTP/1.0! we do not want our socket to freeze and timeout SuperStrict Type Thttp Field sock:TSocket Field stream:TStream Field host:String Field agent:String = "BlitzThttp/1.0" Field autoClose:Int Method Open:Int(host:String, autoClose:Int = False) Self.sock = CreateTCPSocket() If ConnectSocket(Self.sock, HostIp(host), 80) Self.host = host Self.stream = CreateSocketStream(Self.sock) Self.autoClose = autoClose Return True Else Return False End If End Method Method Get:String(get:String = "") Local buffer:String WriteLine(stream, "GET /" + get + " HTTP/1.0~nHost: " + Self.host + "~nUser-Agent: " + Self.agent + "~n~n") While Not Eof(stream) buffer:+ReadLine(stream) + "~n" Wend If autoClose Close() Return Left(buffer, Len(buffer) - 1) End Method Method Post:String(page:String = "", keys:String[] , values:String[] ) Local buffer:String Local data:String Local i:Int For i = 0 To keys.Length - 1 data:+UrlEncode(keys[i] ) + "=" + UrlEncode(values[i] ) + "&" Next data = Left(data, Len(data) - 1) WriteLine(stream, "POST /" + page + " HTTP/1.0~nHost: " + Self.host + "~nUser-Agent: " + Self.agent + "~nContent-Length: " + Len(data) + "~nContent-Type: application/x-www-form-urlencoded~n~n" + data) While Not Eof(stream) buffer:+ReadLine(stream) + "~n" Wend If autoClose Close() Return Left(buffer, Len(buffer) - 1) End Method Method Close() If Self.stream CloseStream(Self.stream) If Self.sock CloseSocket(Self.sock) End Method Function UrlEncode:String(url:String) Local buffer:String Local Char:Int Local i:Int For i = 1 To Len(url) Char = Asc(Mid(url, i, 1)) If(Char >= 48 And Char <= 57) Or (Char >= 65 And Char <= 90) Or (Char >= 97 And Char <= 122) Or Char = 43 Or Char = 45 Or Char = 46 Or Char = 95 buffer = buffer + Chr(Char) Else buffer = buffer + "%" + Right(Hex(Char), 2) End If Next Return buffer End Function Function UrlDecode:String(url:String) Local sHex:String = "0123456789ABCDEF" Local buffer:String Local i:Int For i = 1 To Len(url) If Mid(url, i, 1) = "%"Then buffer = buffer + Chr(Instr(sHex, Mid(url, i + 1, 1)) Shl 4 + Instr(sHex, Mid(url, i + 2, 1)) - 17) i:+2 Else buffer = buffer + Mid(url, i, 1) End If Next Return buffer End Function End Type Local http:THTTP = New THTTP 'GET Example If http.Open("www.fantasaar.com") Print http.Get("version.php?client=game") End If http.Close() If http.Open("www.google.com") 'POST Example Print http.Post("/search", ["hl", "q", "btnG"] , ["en", "fantasaar", "Google Search"] ) End If http.Close()