Low-Level API
To use the low-level API, first create a URL instance via urlAlloc:
Url *url = urlAlloc();
When finished, free the URL with urlClose.
The primary low-level API is urlFetch. This API supports issuing any HTTP method with body data and headers.
urlFetch
int status = urlFetch(url, "POST", "https://my.com/data", data, dataLength, NULL);
This call returns a HTTP status code. To retrieve the returned data, use urlGetResponse or urlGetJsonResponse:
urlGetResponse
char *data = urlGetResponse(url);
// or
Json *json = urlGetJsonResponse(url);
urlFetchJson
You can also use the JSON variant urlFetchJson which returns the JSON tree if the HTTP return status is a successful 200 code.
Json *json urlFetchJson(url, "POST", "https://my.com/data", data, dataLength, NULL);
In this case, you can call urlGetStatus to return the HTTP status code.
urlGetHeader
To retrieve returned HTTP headers, use urlGetHeader:
cchar *length = urlGetHeader(url, "Content-Length");
Streaming
The Ioto URL client fully supports streaming data in both directions.
To start a streaming request, use urlStart. Then write data blocks with urlWrite.
When complete, write a NULL block to signify the end of the posted data.
urlStart(url, "POST", "https://my.com/data");
urlWriteHeaders(url, "X-Custom: %s\r\n", "custom-header");
urlWrite(url, data, dataLength);
urlWrite(url, moreData, moreDataLength);
// signify end of data
urlFinalize(url0);
To stream the response, use urlRead:
char buf[1024];
do {
if ((nbytes = urlRead(url, buf, sizeof(buf))) == 0) {
// End of input
break;
} else if (nbytes < 0) {
// Error
}
} while (nbytes > 0);
Timeouts
You can define a timeout limit for URL requests incase the server should hang.
urlSetTimeout(url, timeInMillisconds);
// or set for all requests
urlSetDefaultTimeout(timeInMillisconds);