Xbase++
Xbase++
HTTP POST and Stream Response to File
See more REST Examples
Demonstrates how to send an HTTP POST and stream the response body directly to a file.Chilkat Xbase++ Downloads
LOCAL nSuccess
LOCAL oRest
LOCAL oUrl
LOCAL nBAutoReconnect
LOCAL nResponseStatusCode
LOCAL oBodyStream
LOCAL cErrResponse
nSuccess := 0
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
oRest := CreateObject("Chilkat.Rest")
oUrl := CreateObject("Chilkat.Url")
// This URL will emit a response that echos the query params (name and age)
oUrl:ParseUrl("https://www.chilkatsoft.com/readPost.asp")
// Connect to the web server
nBAutoReconnect := 1
nSuccess := oRest:Connect(oUrl:Host, oUrl:Port, oUrl:Ssl, nBAutoReconnect)
IF (nSuccess != 1)
? oRest:LastErrorText
oRest:destroy()
oUrl:destroy()
RETURN
ENDIF
oRest:AddQueryParam("name", "John")
oRest:AddQueryParam("age", "33")
// Send the HTTP POST.
nSuccess := oRest:SendReqFormUrlEncoded("POST", oUrl:Path)
IF (nSuccess != 1)
? oRest:LastErrorText
oRest:destroy()
oUrl:destroy()
RETURN
ENDIF
// Read the response header.
nResponseStatusCode := oRest:ReadResponseHeader()
IF (nResponseStatusCode < 0)
? oRest:LastErrorText
oRest:destroy()
oUrl:destroy()
RETURN
ENDIF
? "Response status code = " + Str(nResponseStatusCode)
// We expect a 200 response status if the file data is coming.
// Otherwise, we'll get a string response body with an error message(or no response body).
IF (nResponseStatusCode == 200)
oBodyStream := CreateObject("Chilkat.Stream")
// The stream's sink will be a file.
oBodyStream:SinkFile := "qa_output/out.txt"
// Read the response body to the stream. Given that we've
// set the stream's sink to a file, it will stream directly
// to the file.
nSuccess := oRest:ReadRespBodyStream(oBodyStream, 1)
IF (nSuccess != 1)
? oRest:LastErrorText
oRest:destroy()
oUrl:destroy()
oBodyStream:destroy()
RETURN
ENDIF
? "Successfully streamed the response to a file."
ELSE
cErrResponse := oRest:ReadRespBodyString()
IF (oRest:LastMethodSuccess != 1)
? oRest:LastErrorText
ELSE
? cErrResponse
ENDIF
ENDIF
oRest:destroy()
oUrl:destroy()
oBodyStream:destroy()