RingDotNetfor Ring

HttpClient in depth

Headers in both directions, status codes that are answers and not errors, EnsureSuccessStatusCode, canceling a request, and saving a download to a file without holding it in memory. A small server in the same program makes it work without the internet.

What you will learn#

The tutorial A REST client made a first REST client; the tutorial HTTP explained HTTP. This lesson adds what you need for real services.

The program#

The service is a small WebServer that runs in the same program (the client code is the same for a real service; only the address differs).

samples/UsingDotNet/tutorials/ch07_http_client.ring
# HttpClient in depth - headers both ways, status codes, errors, time limits, cancelling and saving a download
#   (a small server runs inside the program, so no internet is needed; the client code is what you write for a real service)
load "dotnet.ring"

using {
	"System"
	"System.IO"
	"System.Net.Http"
	"System.Threading"
	"RingDotNet.Web"
}

oServer = ""
oClient = ""

func main

	oServer = new WebServer("http://127.0.0.1:0")
	oServer.onGet("/echo","echoPage")
	oServer.onGet("/status","statusPage")
	oServer.onGet("/slow","slowPage")
	oServer.onGet("/file","filePage")

	# One HttpClient for the whole program: it keeps connections open. DefaultRequestHeaders are sent with EVERY request.
	oClient = new HttpClient()
	oTimeout = new TimeSpan().FromSeconds(10)
	oClient.Timeout = oTimeout
	oClient.DefaultRequestHeaders.Add("X-Client","ringdotnet-http-client")
	oClient.DefaultRequestHeaders.Add("Accept","text/plain")

	# 1. Headers in both directions. The client sent X-Client; the server answers with its own header X-Server and a content type.
	oResponse = fetchPage("/echo?name=Ann")
	? "1. status: " + oResponse.StatusCode + ", body: " + bodyOf(oResponse)
	? "   the server's header X-Server: " + oResponse.Headers.GetValues("X-Server").toList()[1]
	? "   content type: " + oResponse.Content.Headers.ContentType.ToString()

	# 2. Status codes. A code of the 200s means success; anything else is an ANSWER, not an error: the call itself worked.
	? nl + "2. what the server says for different codes:"
	for nCode in [200,201,404,500]
		oResponse = fetchPage("/status?code=" + nCode)
		? "   " + nCode + " -> " + oResponse.StatusCode + " (" + oResponse.ReasonPhrase + "), success: " + yesNo(oResponse.IsSuccessStatusCode)
	next

	# 3. EnsureSuccessStatusCode turns a bad status into an error. Use it when "not OK" means "stop here".
	oResponse = fetchPage("/status?code=404")
	try
		oResponse.EnsureSuccessStatusCode()
		? nl + "3. (no error)"
	catch
		? nl + "3. EnsureSuccessStatusCode raised: " + substr(left(cCatchError,70),nl," ")
	done

	# 4. Canceling. A request that takes too long can be canceled: CancelAfter(ms) on a CancellationTokenSource, and its Token goes
	#    with the request. The slow page is never served (nobody calls serveOne), so the request has to be canceled.
	oSource = new CancellationTokenSource()
	oSource.CancelAfter(300)
	oTask = oClient.GetAsync([ :requestUri = oServer.url() + "/slow", :cancellationToken = oSource.Token ])
	lCanceled = False
	try
		oTask.Wait(NULL)
	catch
		lCanceled = True
	done
	? nl + "4. a request canceled after 300 ms: canceled = " + yesNo(lCanceled) + ", the task says canceled: " + yesNo(oTask.IsCanceled)
	oSource.Dispose()

	# 5. Save a download to a file: copy the content to a FileStream. The whole body is never held in memory.
	cFile = new Path().Combine([new Path().GetTempPath(),"ringdotnet_http_client.txt"])
	oResponse = fetchPage("/file")
	oStream = new File().Create(cFile)
	oCopy = oResponse.Content.CopyToAsync(oStream)
	oCopy.Wait(NULL)
	oStream.Dispose()
	? nl + "5. the download was saved: " + new FileInfo(cFile).Length + " bytes, the first line is '" + new File().ReadAllLines(cFile).toList()[1] + "'"
	new File().Delete(cFile)

	oServer.close()

# send a GET request, serve it (the server lives in this program) and return the HttpResponseMessage
func fetchPage cPath

	oTask = oClient.GetAsync(oServer.url() + cPath)
	for nTry = 1 to 100
		oServer.serveOne(50)                   # serve what is waiting (also requests that nobody waits for any more)
		if oTask.IsCompleted
			exit
		ok
	next
	oTask.Wait(NULL)
	return oTask.Result

func bodyOf oResponse

	oBody = oResponse.Content.ReadAsStringAsync(NULL)
	oBody.Wait(NULL)
	return oBody.Result

func yesNo lValue

	if lValue
		return "yes"
	ok
	return "no"

# ---------------------------------------------------------------- the pages of the little server

func echoPage oRequest

	oRequest.setHeader("X-Server","ring")
	return [200,"text/plain","hello " + oRequest.query("name") + ", your header X-Client was: " + oRequest.header("X-Client")]

func statusPage oRequest

	return [number(oRequest.query("code")),"text/plain","status page"]

func slowPage oRequest

	return [200,"text/plain","never sent"]

func filePage oRequest

	cText = "first line of the file" + nl
	for nLine = 2 to 400
		cText += "line number " + nLine + " of a long file" + nl
	next
	return [200,"text/plain",cText]
Output
1. status: OK, body: hello Ann, your header X-Client was: ringdotnet-http-client
   the server's header X-Server: ring
   content type: text/plain; charset=utf-8

2. what the server says for different codes:
   200 -> OK (OK), success: yes
   201 -> Created (Created), success: yes
   404 -> NotFound (Not Found), success: no
   500 -> InternalServerError (Internal Server Error), success: no

3. EnsureSuccessStatusCode raised: DotNet Error: System.Net.Http.HttpRequestException: Response status co

4. a request canceled after 300 ms: canceled = yes, the task says canceled: yes

5. the download was saved: 12286 bytes, the first line is 'first line of the file'

How it works#

One client#

Create one HttpClient and use it for all requests: it keeps connections open and is meant to be shared. Creating a client for each request wastes connections. DefaultRequestHeaders.Add("X-Client", …) adds headers that go with every request (a user agent, an API key, Accept). The timeout of ten seconds protects the program from a server that never answers.

Headers#

Step 1 shows both directions. The request carried X-Client; the page read it with oRequest.header("X-Client"). The page set its own header with oRequest.setHeader("X-Server","ring"), and the client reads it with oResponse.Headers.GetValues("X-Server") (a header can have several values, so it gives a collection: .toList()[1] is the first). Headers about the body are on oResponse.Content.Headers: ContentType says what kind of data it is and in which encoding.

Status codes#

oResponse.StatusCode is a text (OK, Created, NotFound, InternalServerError), ReasonPhrase the standard words, and IsSuccessStatusCode is true for the 200s. A 404 is an answer from the server: the request worked, the thing is not there. Your program decides what that means.

EnsureSuccessStatusCode#

When anything but success means "stop", call oResponse.EnsureSuccessStatusCode(): it raises an HttpRequestException that says which code came, and your try / catch handles it in one place (the tutorial When things go wrong).

Canceling#

A CancellationTokenSource (the tutorial Tasks that wait) with CancelAfter(300) and its token in GetAsync([ :requestUri = …, :cancellationToken = oSource.Token ]) cancels a request that is not finished after 300 ms. In the tutorial the /slow page is simply never served, so only the cancel can end it; the task ends canceled and Wait raises an error. This is how a window program offers a Cancel button: the click calls oSource.Cancel().

Note

The little server lives in this program and handles requests only while the program calls serveOne. The helper fetchPage keeps serving until its own request is finished, so it also serves requests of earlier, canceled calls. A real server runs elsewhere and does not need that.

Saving a download#

oResponse.Content.CopyToAsync(oStream) copies the body into a file stream in pieces; Wait(NULL) waits for it. A big file is never held in memory as a whole. Dispose the stream afterwards. For a really big download ask for the headers first (HttpCompletionOption.ResponseHeadersRead) so that the body is not buffered before you copy it.

What you learned#

Exercises#

  1. Add a header Authorization with a fake token and let the server answer 401 when it is missing.
  2. Download the file with ResponseHeadersRead and print the ContentLength from the headers before copying.
  3. Send three requests together and wait with WhenAll (the tutorial Tasks that wait).
  4. Retry a request three times with a pause when the status is 503.

Next#

A REST client

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.