| request - a request from HttpRequest |
|
Returns the answer to a request, as text. Read it once HttpStatus is above 0; before that it may be empty or only part of the answer. It is the answer's bytes as they came, which for text from the web is almost always UTF-8, so accents and other alphabets come through as they should. A JSON answer, which is what most web services send, goes straight into ParseJson. An error page is an answer too: when the status is 404 or 500, HttpText is whatever the server sent with it, which often says what went wrong. An answer that went into a saveTo$ file is not kept in memory, so HttpText returns "" for it. Pictures, sounds, models and other files that aren't text belong in a file: give HttpRequest a saveTo$ and load the file when it is there. See also: HttpRequest, HttpStatus, HttpHeader, ParseJson. |
; HttpRequest Example
; -------------------
Graphics 640,480,0,2
SetBuffer BackBuffer()
; The Khronos Group's list of glTF sample models: a JSON file on GitHub
url$="https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/model-index.json"
; Start the request: HttpRequest returns at once, and the answer
; arrives while the program carries on
request=HttpRequest(url)
; The first 20 model names, once the answer is in
Dim names$(19)
count=0
unread=True
While Not KeyDown(1)
; Space asks again
If KeyHit(57) Then
FreeHttpRequest request
request=HttpRequest(url)
unread=True
count=0
EndIf
; HttpStatus is 0 while the request runs, then the HTTP status
status=HttpStatus(request)
If status=200 And unread Then
; The answer is text: here, a JSON array of models
index=ParseJson(HttpText(request))
If index Then
count=JsonCount(index)
For i=0 To 19
If i<count Then
model=JsonArrayGet(index,i)
label=JsonObjectGet(model,"label")
names(i)=JsonText(label)
FreeJson label
FreeJson model
EndIf
Next
FreeJson index
EndIf
unread=False
EndIf
Cls
Text 0,0,"Space: ask again Esc: exit"
If status=0 Then
Text 0,20,"Asking GitHub for the glTF sample models..."
ElseIf status<0 Then
; Below 0, the request ended without an answer
Text 0,20,"No answer: "+HttpError(request)
Else
Text 0,20,"HttpStatus: "+status+" Content-Type: "+HttpHeader(request,"Content-Type")
Text 0,40,count+" models; the first 20:"
For i=0 To 19
Text 20,70+i*20,names(i)
Next
EndIf
; Waiting a frame lets the answer arrive, on the web too
Flip
Wend
FreeHttpRequest request
End