HTTP

Requests to web servers, and URLs.

x has its own HTTP/1.1 client, the same on Windows and Linux. Its requests go out as PureBasic's (curl's) do, with the same user agent (Mozilla/5.0 Gecko/41.0 Firefox/41.0) and the same answers to HTTPInfo. Compatible with PureBasic 6.50: the constants, the request sent, status codes and headers, redirects, #PB_HTTP_HeadersOnly, failures, asynchronous requests, ReceiveHTTPMemory and ReceiveHTTPFile.

  • https: on Windows, through Windows' own TLS (SChannel), checking the server's certificate unless #PB_HTTP_NoSSLCheck. On Linux, not yet: an https request fails, with an error message saying so.
  • Where x differs:
    • It doesn't ask for gzip-compressed answers (it can't unpack them yet).
    • The program's headers go out in the order they were added (PureBasic: its map's hash order).
    • Proxies: HTTP proxies only, and not for https.
    • #PB_HTTP_WeakSSL and #PB_HTTP_Debug do nothing.

Requests

HTTPRequest ✅, HTTPRequestMemory ✅

HttpRequest = HTTPRequest(Type, URL$ [, Data$ [, Flags [, Headers()]]])
HttpRequest = HTTPRequestMemory(Type, URL$ [, *Data, DataSize [, Flags [, Headers()]]])

Sends a request, with text (as UTF-8) or bytes, and waits for the answer (unless #PB_HTTP_Asynchronous). Returns the request, for the functions below; always call FinishHTTP once done with it. A request that can't get an answer (no such site, refused) still returns a request: its status code is 0 and HTTPInfo(…, #PB_HTTP_ErrorMessage) says why.

Type Flags
#PB_HTTP_Get (0) #PB_HTTP_Asynchronous don't wait: see HTTPProgress
#PB_HTTP_Post (1) #PB_HTTP_NoRedirect don't follow redirections
#PB_HTTP_Put (2) #PB_HTTP_NoSSLCheck https: don't check the certificate
#PB_HTTP_Patch (3) #PB_HTTP_HeadersOnly the headers only (a HEAD request)
#PB_HTTP_Delete (4)

Headers() is a map of the program's own headers: Header$("Content-Type") = "application/json".

HTTPInfo ✅

Text$ = HTTPInfo(HttpRequest, Type [, Flags])
Type
#PB_HTTP_StatusCode "200", "404", … ("0": no answer)
#PB_HTTP_Response the answer's body, as text (Flags: #PB_UTF8, the default, or #PB_Ascii)
#PB_HTTP_Headers the answer's headers, from the status line to the empty line
#PB_HTTP_ErrorMessage why it failed, or ""

HTTPMemory ✅

*Buffer = HTTPMemory(HttpRequest)

The answer's body as bytes, in new memory (free it with FreeMemory).

HTTPProgress ✅, AbortHTTP ✅, FinishHTTP ✅

Result = HTTPProgress(HttpRequest)
AbortHTTP(HttpRequest)
Result = FinishHTTP(HttpRequest)

An asynchronous request moves on each time HTTPProgress is called: it returns the bytes received so far, then #PB_HTTP_Success (-2), #PB_HTTP_Failed (-3) or #PB_HTTP_Aborted (-4, after AbortHTTP). FinishHTTP frees the request; for ReceiveHTTPFile it returns the bytes written, for an asynchronous ReceiveHTTPMemory the memory with the body.

ReceiveHTTPMemory ✅, ReceiveHTTPFile ✅

*Buffer = ReceiveHTTPMemory(URL$ [, Flags [, UserAgent$]])
Result = ReceiveHTTPFile(URL$, Filename$ [, Flags [, UserAgent$]])

Downloads into new memory, or into a file. As in PureBasic, a page the server answers with an error (404) still counts: the memory or file holds the server's error page.

HTTPTimeout ✅, HTTPProxy ✅

HTTPTimeout(ConnectTimeout [, GlobalTimeout])
HTTPProxy(URL$ [, User$, Password$])

How long to wait for a connection (30 seconds by default; #PB_Default puts it back) and for a whole request (no limit by default). An HTTP proxy for the requests that follow ("": none).

A request to a little server in the same program:

OpenConsole()
Procedure Server(port)
  Protected *b = AllocateMemory(10000), n, body$
  Repeat
    If NetworkServerEvent() = #PB_NetworkEvent_Data
      n = ReceiveNetworkData(EventClient(), *b, 10000)
      body$ = "You asked for " + StringField(PeekS(*b, n, #PB_UTF8 | #PB_ByteLength), 2, " ")
      SendNetworkString(EventClient(), "HTTP/1.1 200 OK" + #CRLF$ + "Content-Length: " + Str(Len(body$)) + #CRLF$ + #CRLF$ + body$)
      Break
    EndIf
    Delay(5)
  ForEver
EndProcedure

If CreateNetworkServer(0, 6841, #PB_Network_TCP, "127.0.0.1")
  CreateThread(@Server(), 0)
  request = HTTPRequest(#PB_HTTP_Get, "http://127.0.0.1:6841/index.html")
  PrintN(HTTPInfo(request, #PB_HTTP_StatusCode) + ": " + HTTPInfo(request, #PB_HTTP_Response))
  FinishHTTP(request)
EndIf

Output:

200: You asked for /index.html

URLs

A URL's parts: protocol://user:password@site:port/path?parameters#fragment.

GetURLPart ✅

Result$ = GetURLPart(URL$, Part$)

A part of the URL, or "". Part$ is one of the constants, or a parameter's name (its value is returned as written, still encoded):

Part$
#PB_URL_Protocol https
#PB_URL_User, #PB_URL_Password
#PB_URL_Site www.example.com
#PB_URL_Port 8080
#PB_URL_Path dir/page.html (without the first /)
#PB_URL_Parameters a=1&b=2 (without ? and #…)

SetURLPart ✅

Result$ = SetURLPart(URL$, Part$, Value$)

The URL with a part changed, or a parameter changed (added at the end, if it isn't there). The value is put in as it is: URLEncoder encodes it.

URLEncoder ✅, URLDecoder ✅

Result$ = URLEncoder(URL$ [, Format])
Result$ = URLDecoder(URL$ [, Format])

Encode: every character but letters, digits and - _ . ~ ! * ' ( ) ; / ? : @ & = $ , # becomes %XX, of its UTF-8 bytes (Format #PB_UTF8, the default) or of itself (#PB_Ascii). Decode: the reverse, with + as a space; a % not followed by two hex digits ends it.

Non-ASCII characters are encoded as UTF-8: é becomes %C3%A9.

OpenConsole()
url$ = "https://www.example.com:8080/shop/list.html?item=tea%20pot&n=2#top"
PrintN(GetURLPart(url$, #PB_URL_Site) + " " + GetURLPart(url$, #PB_URL_Port) + " " + GetURLPart(url$, #PB_URL_Path))
PrintN(GetURLPart(url$, "item") + " -> " + URLDecoder(GetURLPart(url$, "item")))
PrintN(SetURLPart(url$, "n", "3"))
PrintN(URLEncoder("search?q=café au lait"))

Output:

www.example.com 8080 shop/list.html
tea%20pot -> tea pot
https://www.example.com:8080/shop/list.html?item=tea%20pot&n=3#top
search?q=caf%C3%A9%20au%20lait

Not yet available 🔜

  • https on Linux (x's own TLS).
  • gzip-compressed answers, SOCKS proxies, https through a proxy.

eXperimental is an independent implementation: no proprietary PureBasic source code or implementation code is incorporated into it. PureBasic is a product of Fantaisie Software. eXperimental is neither affiliated with nor endorsed by Fantaisie Software.