Chapter 3 Sending HTTP Requests

Sending an HTTP request

After an HTTP request is created, send it using one of the following methods:

Delete()

method Delete(location As %String = "", 
              test As %Integer = 0, 
              reset As %Boolean = 1) as %Status
Copy the code

Issue an HTTP DELETE request.

Get()

method Get(location As %String = "", 
           test As %Integer = 0, 
           reset As %Boolean = 1) as %Status
Copy the code

Send an HTTP GET request. This method causes the Web server to return the requested page.

Head()

method Head(location As %String, 
            test As %Integer = 0, 
            reset As %Boolean = 1) as %Status
Copy the code

Issue an HTTP Head request. This method causes the Web server to return only the response header, not the body.

Patch()

method Patch(location As %String = "", 
             test As %Integer = 0, 
             reset As %Boolean = 1) as %Status
Copy the code

Issue an HTTP patch request. You can use this method to make partial changes to existing resources.

Post()

method Post(location As %String = "", 
            test As %Integer = 0, 
            reset As %Boolean = 1) as %Status
Copy the code

Make an HTTP POST request. Use this method to send data, such as form results, to a Web server or to upload files. See “Sending Form Data” for an example.

Put()

method Put(location As %String = "", 
           test As %Integer = 0, 
           reset As %Boolean = 1) as %Status
Copy the code

Send an HTTP PUT request. Use this method to upload data to the Web server. PUT requests are not common.

Send()

method Send(type As %String, 
            location As %String, 
            test As %Integer = 0, 
            reset As %Boolean = 1) as %Status
Copy the code

Sends an HTTP request of the specified type to the server. This method is usually called by other methods, but is provided for use if you want to use a different HTTP predicate. Here type is a string specifying an HTTP predicate such as “POST”.

In all cases:

  • Each method returns a state that should be checked.
  • If this method completes correctly, the response to this request will be locatedHttpResponseAttribute.
  • LocationThe argument is the URL to request, for example:"/test.html".
  • LocationParameters can contain parameters, assuming they have been URL escaped, for example:"/test.html? PARAM=%25VALUE"willPARAMSet to equal%VALUE.
  • Use the test parameter to check that you are sending what you expect to send:
    • If test is 1, the method does not connect to the remote machine, but outputs to the current device what it should have sent to the Web server.
    • iftestfor2, is emittedHTTPThe request outputs the response to the current device.
  • Each method is automatically invoked after the response is read from the serverReset()Method, unlesstest=1orReset=0.

The Reset() method resets the % net.Httprequest instance so that it can make another request. This is much faster than closing the object and creating a new instance. This also moves the value of the Location header to the Referer header.

 Set httprequest=##class(%Net.HttpRequest%).New(a)Set httprequest.Server="www.intersystems.com"
 Do httprequest.Get("/")
 
Copy the code

Create and send a multi-part POST request

To create and send multipart POST requests, use the % net.mimepart class, which is discussed in detail later in this book. The following example sends a two-part POST request. The first part contains the binary data of the file and the second part contains the file name.

ClassMethod CorrectWriteMIMEMessage3(header As %String)
{
     // Create root MIMEPart
     Set RootMIMEPart=##class(%Net.MIMEPart%).New(a) / /Create binary subpart and insert file data
     Set BinaryMIMEPart= # #class(%Net.MIMEPart%).New(a)Set contentdisp="form-data; name="_$CHAR(34) _"file"_$CHAR(34) _"; filename="
                     _$CHAR(34) _"task4059.txt"_$CHAR(34)
     Do BinaryMIMEPart.SetHeader("Content-Disposition",contentdisp)

     Set stream=##class(%FileBinaryStream%).New(a)Set stream.Filename="/home/tabaiba/prueba.txt"
     Do stream.LinkToFile("/home/tabaiba/prueba.txt")

     Set BinaryMIMEPart.Body=stream
     Do BinaryMIMEPart.SetHeader("Content-Type"."text/plain")

    // Create text subpart
    Set TextMIMEPart=##class(%Net.MIMEPart%).New(a)Set TextMIMEPart.Body= # #class(%GlobalCharacterStream%).New(a)Do TextMIMEPart.Body.Write(" /home/tabaiba/prueba.txt/ / ")specify some headers
    Set TextMIMEPart.ContentType="text/plain"
    Set TextMIMEPart.ContentCharset="us-ascii"
    Do TextMIMEPart.SetHeader("Custom-header",header)

    // Insert both subparts into the root part
    Do RootMIMEPart.Parts.Insert(BinaryMIMEPart)

    // create MIME writer; write root MIME message
    Set writer=##class(%Net.MIMEWriter%).New(a) / /Prepare outputting to the HttpRequestStream
    Set SentHttpRequest= # #class(%Net.HttpRequest%).New(a)Set status=writer.OutputToStream(SentHttpRequest.EntityBody)
    if $$$ISERR(status) {do $SYSTEM.Status.DisplayError(status) Quit}

    // Now write down the content
    Set status=writer.WriteMIMEBody(RootMIMEPart)
    if $$$ISERR(status) {do $SYSTEM.Status.DisplayError(status) Quit}

    Set SentHttpRequest.Server="congrio"
    Set SentHttpRequest.Port = 8080

    Set ContentType= "multipart/form-data; boundary="_RootMIMEPart.Boundary
    Set SentHttpRequest.ContentType=ContentType

    set url="alfresco/service/sample/upload.json?"
            _"alf_ticket=TICKET_caee62bf36f0ea5bd51194fce161f99092b75f62"

    set status=SentHttpRequest.Post(url,0) 
    if $$$ISERR(status) {do $SYSTEM.Status.DisplayError(status) Quit}
}
Copy the code

Access HTTP response

After an HTTP request is sent, the request’s HttpResponse attribute is updated. This property is an instance of % net.Httpresponse. This section describes how to use a Response object. It includes the following topics:

Access the data of the response

The body of the HTTP response is contained in the Data property of the response. This property contains stream objects (specifically %GlobalBinaryStream). To use this stream, use the standard stream methods: Write(), WriteLine(), Read(), ReadLine(), Rewind(), MoveToEnd(), and Clear(). You can also use the Size attribute of the stream.

The request’s ReadRawMode property controls how the response body is read.

  • By default, this property is False, and InterSystems IRIS assumes that the body is in the responseHTTPIn the character set specified in the header (and converts the character set accordingly).
  • If this property is true, InterSystems IRIS reads the body in raw mode (no character set conversion is performed).

You can also use the OutputToDevice() method, which writes the complete response to the current device. The order of the headers is different from the order generated by the Web server.

Here is a simple example where we copy the response stream to a file and save it:

/// w ##class(PHA.TEST.HTTP).Stream()
ClassMethod Stream(a)
{
	set request=##class(%Net.HttpRequest%).New(a)set request.Server="tools.ietf.org"
	set request.Https=1
	set request.SSLConfiguration="yx"
	set status=request.Get("/html/rfc7158")
	if $$$ISERR(status) {
	     do $system.OBJ.DisplayError()
	} else {
	     set response=request.HttpResponse
	}

	Set file=##class(%FileCharacterStream%).New(a)set file.Filename="e:/temp/rfc7158.txt"
	set status=file.CopyFrom(response.Data)
	if $$$ISERR(status) {
	     do $system.OBJ.DisplayError()
	}
	do file.%Close()
	q ""
}
Copy the code

Gets HTTP headers by name

The % net.Httpresponse class stores its HTTP headers in InterSystems IRIS multidimensional arrays. To access the header, use the following method:

GetHeader()

Returns the value of the given header.

GetNextHeader()

Returns the name of the next header after the calibration.

Each of these methods takes only one parameter, the name string of the HTTP header.

You can also use the OutputHeaders() method, which writes HTTP headers to the current device (although they are generated in a different order).

Access additional information about the response

The % net.httpresponse class provides properties that store other specific parts of the HTTP response:

  • StatusLineStores the HTTP status line, which is the first line of the response.
  • StatusCodeStores HTTP status codes.
  • ReasonPhraseThe storage andStatusCodeCorresponding human readable causes.
  • ContentInfoStores additional information about the response body.
  • ContentTypeStore theContent-Type:The value of the header.
  • HttpVersionRepresents the VERSION of HTTP supported by the Web server sending the response.