Back to Contents


The HTTP Request class

Summary:

See also: The Genero Web Services COM Extension Library


Syntax

The HTTP Request class provides an interface to perform asynchronous XML and TEXT requests over HTTP for a specified URL, with additional XML streaming possibilities.

Note that status is set to zero after a successful method call.

Syntax

com.HTTPRequest

Methods


Creation

Class Methods
Name Description
com.HTTPRequest.Create(
  url
STRING )
   
RETURNING com.HTTPRequest
Creates an HTTPRequest object by providing a mandatory url with HTTP or HTTPS as the protocol.
Note: url can be an identifier of an URL mapping with an optional alias:// prefix. See FGLPROFILE Configuration for more details about URL mapping with aliases, and for proxy and security configuration.
Throws an exception in case of errors, and updates status with an error code.

Back to the top


Configuration

Object Methods
Name Description
setVersion(
  version
STRING )
Sets the HTTP version of the request.
Note: Only 1.0 and 1.1 are supported. Default is 1.1.
Throws an exception in case of errors, and updates status with an error code.
setMethod(
  method
STRING )
Sets the HTTP method of the request.
Note: Supported methods are GET, PUT, POST, HEAD and DELETE. Default is GET.
Throws an exception in case of errors, and updates status with an error code.
setHeader(
  name
STRING,
  value
STRING )
Sets an HTTP header name and value for the request, and replaces the previous one if there was any.
Note: Setting a header after the body has been sent, or if a streaming operation has been started, will only be taken into account when a new request is reissued.
Throws an exception in case of errors, and updates status with an error code.
removeHeader(
  name
STRING )
Removes an HTTP header name for the request if it exists.
Throws an exception in case of errors, and updates status with an error code.
clearHeaders() Removes all user-defined headers.
setCharset(
  charset
STRING )
Defines the charset used when sending text or XML; by default no charset is set.
Note: When sending text, HTTP specification defines ISO-8859-1 as an implicit charset.
Note: When sending XML, the user-defined charset is used instead of the one set in the XML document itself, which can lead to a charset conversion error at the server side. Therefore it is recommended that you unset it by setting charset to NULL, or that you use the same charset that was set in the XML Document.
setAuthentication(
  login
STRING,
  password
STRING,
  scheme
STRING,
  realm
STRING )
Defines the mandatory user login and password to authenticate to the server.
An optional scheme defines the method to be used during authentication.
Note:
 Only Anonymous, Basic and Digest are supported. Default is Anonymous.
An optional realm can also be set.
Note:
  With Anonymous or Digest authentication, you must resend the request if you get a 401 or 407 HTTP return code (authorization required)
Note:
  If a user-defined authentication is set and there is an authenticate entry for this URL in the FGLPROFILE file, the user-defined has priority.
Throws an exception in case of errors, and updates status with an error code.
clearAuthentication() Removes user-defined authentication.
Note:
 If an authenticate entry exists in the FGLPROFILE file, it will be used for authentication, even if the user-defined was removed.
setKeepConnection(
  keep
INTEGER )
Defines whether the connection should stay open if a new request occurs again. Default is FALSE.
setTimeOut(
  timeout
INTEGER )
Sets the time value in seconds to wait for a reading or writing operation, before a break.
Note: -1 means infinite.
setConnectionTimeOut(
  timeout
INTEGER )
Sets the time value in seconds to wait for the establishment of the connection, before a break.
Note: -1 means infinite.
setMaximumResponseLength(
  length
INTEGER )
Sets the maximum authorized size in Kbyte of the whole response (composed of the headers, the body and all control characters), before a break.
Note: -1 means no limit.

Back to the top


Sending

Object Methods
Name Description
doRequest() Performs the request. Supported methods are GET, HEAD and DELETE.
Throws an exception in case of errors, and updates status with an error code.
doTextRequest(
  txt
STRING )
Performs the request by sending an entire string at once. Supported methods are PUT and POST.
Note: The default Content-Type header is text/plain, but it can be changed if of the form text/*, for instance text/richtext.
Note: Automatic conversion from locale to user-defined charset is performed when possible, otherwise throws an exception.
Note: In HTTP 1.1, if the body size is greater than 32k, the request will be sent in several chunks of the same size.
Throws an exception in case of errors, and updates status with an error code.
doXmlRequest(
  doc xml.DomDocument )
Performs the request by sending the entire xml.DomDocument at once. Supported methods are PUT and POST.
Note: The default Content-Type header is text/xml, but it can be changed if of the form */xml or */*+xml, for instance application/xhtml+xml.
Note: In HTTP 1.1, if the body size is greater than 32k, the request will be sent in several chunks of the same size.
Throws an exception in case of errors, and updates status with an error code.
doFormEncodedRequest(
  query
STRING,
  utf8
INTEGER )
Performs an application/x-www-form-urlencoded Forms encoded query. Supported methods are GET and POST. The query string is a list of name/value pairs separated with &. For example, name1=value1&name2=value2&name3=value3.
Note: If utf8 is TRUE, the query string is encoded in UTF-8 as specified in XForms 1.0, otherwise in ASCII as specified in HTML 4.
Throws an exception in case of errors, and updates status with an error code.
beginXmlRequest()
   RETURNING
xml.StaxWriter
Begins the streaming HTTP request and returns an xml.StaxWriter object ready to send XML to the server. Supported methods are PUT and POST.
Note: The default Content-Type header is text/xml, but it can be changed if of the form */xml or */*+xml,  for instance application/xhtml+xml.
Note: In HTTP 1.1, if the body size is greater than 32k, the request will be sent in several chunks of the same size.
Throws an exception in case of errors, and updates status with an error code.
endXmlRequest(
  writer xml.StaxWriter )
Ends the streaming HTTP request by closing the Stax writer.
Throws an exception in case of errors, and updates status with an error code.

Back to the top


Response

Object Methods
Name Description
getResponse()
  
RETURNING com.HTTPResponse
Returns the response of one of the doRequest, doTextRequest, doXmlRequest, doFormEncodedRequest or beginXmlRequest and endXmlRequest calls in an com.HTTPResponse object.
Throws an exception in case of errors, and updates status with an error code.
getAsyncResponse()
   RETURNING
com.HTTPResponse
Returns the response of one of the doRequest, doTextRequest, doXmlRequest, doFormEncodedRequest or beginXmlRequest and endXmlRequest calls in an com.HTTPResponse object, or NULL if the response was not yet received.
Remarks:
If a previous call returned NULL, a new call will return the expected response if it has already arrived, or NULL again if the response was still not received.
Throws an exception in case of errors, and updates status with an error code.

Back to the top


Examples

Example 1 : HTTP GET request

    IMPORT com
    
    MAIN 
      DEFINE req      com.HTTPRequest
      DEFINE resp     com.HTTPResponse

      TRY     
        LET req = com.HTTPRequest.Create("http://localhost:8090/MyPage")
        CALL req.setHeader("MyHeader","High Priority") # Set additional HTTP header with name 'MyHeader', and value 'High Priority'
        CALL req.doRequest()
        LET resp = req.getResponse()
        IF resp.getStatusCode() != 200 THEN
          DISPLAY  "HTTP Error ("||resp.getStatusCode()||") ",resp.getStatusDescription()
        ELSE    
          DISPLAY  "HTTP Response is : ",resp.getTextResponse()
        END IF         
      CATCH
        DISPLAY "ERROR :",STATUS||" ("||SQLCA.SQLERRM||")"      
      END TRY
    END MAIN
    

Example 2 : XForms HTTP POST request

    IMPORT com
    IMPORT xml
    
    MAIN 
      DEFINE req      com.HTTPRequest
      DEFINE resp     com.HTTPResponse
      DEFINE doc      xml.DomDocument

      TRY     
        LET req = com.HTTPRequest.Create("http://localhost:8090/MyProcess")
        CALL req.setMethod("POST") # Perform an HTTP POST method
        CALL req.doFormEncodedRequest("Param1=hello&Param2=how are you ?",FALSE) # Param1 value is 'hello', Param2 value is 'how are you ?'
        LET resp = req.getResponse()
        IF resp.getStatusCode() != 200 THEN
          DISPLAY  "HTTP Error ("||resp.getStatusCode()||") ",resp.getStatusDescription()
        ELSE    
          LET  doc = resp.getXmlResponse() # Expect a returned content type of the form */xml
          DISPLAY  "HTTP XML Response is : ",doc.saveToString()
        END IF         
      CATCH
        DISPLAY "ERROR :",STATUS||" ("||SQLCA.SQLERRM||")"      
      END TRY
    END MAIN
    

Example 3 : Streaming HTTP PUT request

    IMPORT com
    IMPORT xml
    
    MAIN 
      DEFINE req      com.HTTPRequest
      DEFINE resp     com.HTTPResponse
      DEFINE writer   xml.StaxWriter

      TRY     
        LET req = com.HTTPRequest.Create("http://localhost:8090/MyXmlProcess")
        CALL req.setMethod("PUT") # Perform an HTTP PUT method
        CALL req.setHeader("MyHeader","Value of my header")    
        LET writer = req.beginXmlRequest() # Retrieve an xml.StaxWriter to start xml streaming
        CALL writer.startDocument("utf-8","1.0",true)
        CALL writer.comment("My first XML document sent in streaming with genero!!!")    
        CALL writer.startElement("root")
        CALL writer.attribute("attr1","value1")    
        CALL writer.endElement()
        CALL writer.endDocument()
        CALL req.endXmlRequest(writer) # End streaming request
        LET resp = req.getResponse()
        IF resp.getStatusCode() != 201 OR resp.getStatusCode() != 204 THEN
          DISPLAY  "HTTP Error ("||resp.getStatusCode()||") ",resp.getStatusDescription()
        ELSE    
          DISPLAY  "XML document was correctly put on the server"
        END IF         
      CATCH
        DISPLAY "ERROR :",STATUS||" ("||SQLCA.SQLERRM||")"      
      END TRY
    END MAIN
    

Example 4 : Asynchronous HTTP DELETE request

    IMPORT com
    
    MAIN 
      DEFINE req         com.HTTPRequest
      DEFINE resp        com.HTTPResponse
      DEFINE url         STRING
      DEFINE quit        CHAR(1)
      DEFINE questionStr STRING
      DEFINE timeout     INTEGER

      TRY     
        WHILE TRUE
          PROMPT "Enter http url you want to delete ? " FOR url ATTRIBUTE (CANCEL=FALSE)
          LET req = com.HTTPRequest.Create(url)
          CALL req.setMethod("DELETE")
          CALL req.doRequest()
          LET resp = req.getAsyncResponse() # Retrieve asynchronous response for the first time
          CALL Update(resp) RETURNING questionStr,timeout
          WHILE quit IS NULL OR ( quit!="Y" AND quit!="N" )
            PROMPT questionStr FOR CHAR quit ATTRIBUTE (CANCEL=FALSE,ACCEPT=FALSE,SHIFT="up")
              ON IDLE timeout
                IF resp IS NULL THEN # If no response at first try, retrieve it again
                  LET resp = req.getAsyncResponse() # because we have time now !!! 
                  CALL Update(resp) RETURNING questionStr,timeout       
                END IF
            END PROMPT 
          END WHILE
          IF quit == "Y" THEN
            EXIT PROGRAM 
          ELSE
            LET quit = NULL
          END IF
        END WHILE
      CATCH
        DISPLAY "ERROR :",STATUS,SQLCA.SQLERRM
      END TRY
    END MAIN
    
    FUNCTION Update(resp)
      DEFINE resp    com.HTTPResponse
      DEFINE ret     STRING
      IF resp IS NOT NULL THEN
        IF resp.getStatusCode() != 204 THEN
          LET  ret = "HTTP Error ("||resp.getStatusCode()||") :"||resp.getStatusDescription()||". Do you want to quit ? "
        ELSE    
          LET  ret = "HTTP Page deleted. Do you want to quit ? "
        END IF             
        RETURN ret, 0
      ELSE     
        LET ret = "Do you want to quit ? "
        RETURN ret, 1
      END IF 
    END FUNCTION    

Back to the top