17
Sun, Nov
2 New Articles

TechTip: DB2 for i HTTP Functions, Part 2: Request and Response Header Fields

Web Languages
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

Learn how to create request header fields and parse response header fields when making HTTP calls.

 

In the first tip, I introduced the new suite of HTTP functions in DB2 for i 7.1 and demonstrated the HTTPGETCLOB and HTTPGETBLOB scalar functions. I'll continue the topic by considering how to include and retrieve HTTP header information with each request. This tip assumes you have some familiarity with the new HTTP functions and with web development concepts. IBM i 7.1, DB2 PTF group SF99701 Level 23, and Java 6 are required.

Anyone who has done web development knows that HTTP header fields are part of the standard HTTP protocol and are used to pass additional information about an HTTP request or response between the client (usually a browser) and the HTTP server. A "request" is made to the web server each time a web page, web service, or other resource is requested. The "response" consists of the information that the web server returns.

The table below shows a list of common request HTTP header fields (from Wikipedia). Your HTTP-enabled application can set any of these fields when making a request to a web server:

 

HTTP Header Fields

Field Name

Description

Example

Accept

Content types that are acceptable for the response

Accept: text/plain

Accept-Encoding

List of acceptable encodings. See HTTP compression.

Accept-Encoding: gzip, deflate

Accept-Language

List of acceptable human languages for response

Accept-Language: en-US

Authorization

Authentication credentials for HTTP authentication

Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

Cache-Control

Used to specify directives that must be obeyed by all caching mechanisms along the request/response chain

Cache-Control: no-cache

Cookie

An HTTP cookie previously sent by the server with Set-Cookie (in the next table)

Cookie: $Version=1; Skin=new;

Content-Length

The length of the request body in octets (8-bit bytes)

Content-Length: 348

Content-Type

The MIME type of the body of the request (used with POST and PUT   requests)

Content-Type: application/x-www-form-urlencoded

Host

The domain name of the server (for virtual hosting) and the TCP port number on which the server is listening

Host: en.wikipedia.org:80

Pragma

Implementation-specific headers that may have various effects anywhere along the request-response   chain

Pragma: no-cache

Proxy-Authorization

Authorization credentials for connecting to a proxy

Proxy-Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

Range

Request only part of an entity. Bytes are numbered from 0.

Range: bytes=500-999

Referer[sic]

This is the address of the previous web page from which a link to the currently requested page was followed. (The word "referrer" is misspelled in the RFC as well as   in most implementations.)

Referer: http://en.wikipedia.org/

wiki/Main_Page

User-Agent

The user agent string of the user agent

User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:12.0)   Gecko/20100101 Firefox/21.0

 

As you can see, there are things of interest to a DB2 developer, such as "Cookie" (in case you have to set cookie information when exchanging data with a traditional web app) and "Authorization" (for when you have to "login" before accessing a service). When sending information using POST or PUT, Content-Type can be used to specify whether the content is plain text, XML, a jpg image, etc.

Likewise, when an HTTP server sends a response back to a client (such as HTML, XML, or a file), it returns extra information in the form of response header fields. The table below shows a few of them (from Wikipedia):

 

  

Response Header Fields

Field Name

Description

Example

Allow

Valid actions for a specified resource. To be used for a 405 Method not allowed.

Allow: GET, HEAD

Content-Disposition

An opportunity to raise a "File Download" dialogue box for a known MIME type with binary format or suggest a filename for dynamic content. Quotes are necessary with   special characters.

Content-Disposition: attachment; filename="fname.ext"

Content-Encoding

The type of encoding used on the data. See HTTP compression.

Content-Encoding: gzip

Content-Language

The language the content is in

Content-Language: da

Content-Length

The length of the response body in octets (8-bit bytes)

Content-Length: 348

Content-Location

An alternate location for the returned data

Content-Location: /index.htm

Content-MD5

A Base64-encoded binary MD5 sum of the content of the response

Content-MD5: Q2hlY2sgSW50ZWdyaXR5IQ==

Content-Range

Where in a full body message this partial message belongs

Content-Range: bytes 21010-47021/47022

Content-Type

The MIME type of this content

Content-Type: text/html; charset=utf-8

Date

The date and time that the message was sent

Date: Tue, 15 Nov 1994 08:12:31 GMT

Expires

Gives the date/time after which the response is considered stale

Expires: Thu, 01 Dec 1994 16:00:00 GMT

Last-Modified

The last modified date for the requested object, in RFC 2822 format

Last-Modified: Tue, 15 Nov 1994 12:45:26 GMT

Pragma

Implementation-specific headers that may have various effects anywhere along the request-response chain

Pragma: no-cache

Retry-After

If an entity is temporarily unavailable, this instructs the client to try again after a specified period of time (seconds).

Retry-After: 120

Server

A name for the server

Server: Apache/2.4.1 (Unix)

Set-Cookie

An HTTP cookie

Set-Cookie: UserID=JohnDoe; Max-Age=3600; Version=1

Status

The HTTP status of the response

Status: 200 OK

Transfer-Encoding

The form of encoding used to safely transfer the entity to the user. Currently defined methods are chunked, compress, deflate, gzip, identity.

Transfer-Encoding: chunked

WWW-Authenticate

Indicates the authentication scheme that should be used to access the requested entity

WWW-Authenticate: Basic

 

When you surf the web with your favorite web browser, you don't need to pay attention to what's being exchanged in these fields because it's done behind the scenes. However, when programming an HTTP request to, say, communicate with a web service using these DB2 for i tools (or similar tools), the web server may require that portions of the header be populated in a special way.

Since you may be making an HTTP call (of any kind) that requires specifying or inspecting a header field, I'll discuss how to do this with the new DB2 HTTP functions. For example, I wrote a program to communicate with a web service in which the service provider, as a security measure, required a specific value to be placed in the User-Agent header request field. The User-Agent normally holds a description of the browser and host OS, but it can be overridden to anything and this vendor required an override. Without setting this header field appropriately, the application wouldn't work.

 

Parsing the DB2 for i HTTP Response Headers

The HTTP protocol requires header fields to be specified in plain text and follow a certain format (name value pairs, using carriage return and line feed, etc.). Wikipedia covers this. Fortunately, we don't have to worry about that stuff. The DB2 functions use an easy-to-understand XML template to exchange this information. I'll explain how to read the server's response header fields and how to send custom values in the request header fields.

 

To examine the HTTP response header fields returned from a web call, use table function HTTPGETCLOBVERBOSE. This function is similar to HTTPGETCLOB with the exception that it's a table function that returns one row with two columns:

 

  • RESPONSEMSG contains the data returned from the web server (same info as returned by HTTPGETCLOB).
  • RESPONSEHTTPHEADER contains information about the headers returned from the server. These values can be interrogated for error codes and the header field name/value pairs.

Most of the other scalar functions have a VERBOSE table function companion (e.g., HTTPGETBLOB (scalar) and HTTPGETBLOBVERBOSE (table)).

 

Recall the simple Google search example from the first tip that simply returns the HTML results of a Google search for A&W Root Beer:

 

Select SYSTOOLS.HTTPGETCLOB
('https://www.google.com/search?q=A%26W+Root+beer&;client=AS400','')


From SYSIBM.SYSDUMMY1;

 

By invoking the verbose table function, it's possible to review the response header fields that Google.com's web server returns as follows:

 

SELECT * FROM TABLE(SYSTOOLS.HTTPGETCLOBVERBOSE
('https://www.google.com/search?q=A%26W+Root+beer&;client=AS400','')) AS HTTPDATA

 

The RESPONSEMSG column returns the same information as the scalar function HTTPGETCLOB (in this case, HTML search results). The RESPONSEHTTPHEADER column returned the following XML (formatted and abridged):

 

<?xml version="1.0" encoding="UTF-8" ?> 

<httpHeader responseCode="200">

<responseMessage>OK</responseMessage>

<header name="HTTP_RESPONSE_CODE" value="HTTP/1.1 200 OK"/>

<header name="Cache-Control" value="private, max-age=0"/>

<header name="Server" value="gws"/>

<header name="X-XSS-Protection" value="1; mode=block"/>

<header name="Expires" value="-1"/>

<header name="Transfer-Encoding" value="chunked"/>

<header name="X-Frame-Options" value="SAMEORIGIN"/>

<header name="Date" value="Sat, 08 Jun 2013 03:15:43 GMT"/>

<header name="Content-Type" value="text/html; charset=ISO-8859-1"/><header name="Set-Cookie" value="NID=67=PO7G2a7WLH9QQsCaw1Kn-w80EDGbwuzGiV1s7dLXbTZ-AKzX01Pk-JuOXapUOL_RpUEYoPrCdYarz3Ce5u5SeX4L18FO73ve-Yrp70cBCTVGfdKSirT5RVOHMclc0km7; expires=Sun, 08-Dec-2013 03:15:43 GMT; path=/; domain=.google.com; HttpOnly"/>

</httpHeader>

 

Besides the response fields, this XML contains additional information from the HTTP server (shown in bold). The responseCode attribute and the responseMessage contain status messages the server returns. The responseCode attribute should always be a three-character response code. The standard HTTP status code classifications are listed below, many of which your application should be prepared to handle when encountered (from Wikipedia):

  • 1xx InformationalThe request has been received and is continuing the process.
  • 2xx SuccessThis class of status codes indicates the action requested by the client was received, understood, accepted, and processed successfully.
  • 3xx RedirectionThe client must take additional action to complete the request.
  • 4xx Client ErrorThis status code is intended for cases in which the client seems to have erred.
  • 5xx Server ErrorThe server failed to fulfill an apparently valid request.

If a 2xx value (Success) isn't returned, prepare to have the app do something about it. If an application receives a 3xx redirection error, the HTTP functions will by default follow the redirection (except when the redirect specifies a different protocol, such as from HTTP to HTTPS).

 

After the HTTP status is listed, the XML presents a series of <header> elements that contain the header field name/value pairs. The following query will parse the response's status information and the header fields using two instances of the XMLTABLE table function combined with a UNION ALL:

 

WITH ResponseHeader AS (

SELECT XMLPARSE(DOCUMENT RESPONSEHTTPHEADER) as "doc"

FROM TABLE(SYSTOOLS.HTTPGETCLOBVERBOSE
('https://www.google.com/search?q=A%26W+Root+beer&;client=AS400',''))
AS HTTPDATA

)

SELECT 'Response' As Type,HeaderResponse.*

FROM XMLTABLE(
'$doc/httpHeader' PASSING (SELECT "doc" FROM ResponseHeader) as "doc"

COLUMNS

Name VARCHAR(10) PATH '@responseCode',

Value VARCHAR(128) PATH 'responseMessage'

) HeaderResponse

UNION ALL

SELECT 'HeaderField' As Type,HeaderResponse.*

FROM XMLTABLE(
'$doc/httpHeader/header' PASSING (SELECT "doc" FROM ResponseHeader) as "doc"

COLUMNS

Name VARCHAR(128) PATH '@name',

Value VARCHAR(128) PATH '@value'>

) HeaderResponse;

 

The results are shown in this table:

 

 

Query Results

Type

Name

Value

Response

200

OK

HeaderField

HTTP_RESPONSE_CODE

HTTP/1.1 200 OK

HeaderField

Cache-Control

private, max-age=0

HeaderField

Server

gws

HeaderField

X-XSS-Protection

1; mode=block

HeaderField

Expires

-1

HeaderField

Transfer-Encoding

Chunked

HeaderField

X-Frame-Options

SAMEORIGIN

HeaderField

P3P

CP="This is not a P3P policy! See   http://www.google.com/support/accounts/bin/answer.py?hl=en&;answer=151657 for more info."

HeaderField

Date

Thu, 14 Mar 2013 19:00:44 GMT

HeaderField

Content-Type

text/html;   charset=ISO-8859-1

HeaderField

Set-Cookie

NID=67=PO7G2a7WLH9QQsCaw1Kn-w80EDGbwuzGiV1s7dLXbTZ-AKzX01Pk-JuOXapUOL_RpUEYoPrCdYarz3Ce5u5SeX4L18FO73ve-Yrp70cBCTVGfdKSirT5RVOHMclc0km7

 

This query demonstrates how to get the web server's header response (status code, summary, and header fields) simultaneously. In practice, one would normally fetch the response into a variable, check the status info and, if the request is OK, move on to processing the header fields and then the data itself.

Passing Request Headers

As previously discussed, sometimes it's a requirement to pass specific values in a request header to a web server in order for the request to be successful. I mentioned an application I wrote where I had to override the User-Agent field.

So using that simple example, how can an application using the new DB2 for i functions set the User-Agent request field to the arbitrary value of "AS/400" before making the request? The answer is that the DB2 HTTP functions have a second parameter called HTTPHEADER. Although the parameter is defined as a CLOB, it is intended to receive XML data formatted as follows:

<httpHeader>

<header name="User-Agent" value="AS/400"/>

</httpHeader>

This is basically the same format as the response header XML parsed in the prior section. So if HTTPGETBLOB is being used to make an HTTP call, setting the User-Agent field is as simple as slapping in the properly formatted XML in the second parameter:

SELECT SYSTOOLS.HTTPGETBLOB('http://mydomain.com/appext/',

'<httpHeader>

<header name="User-Agent" value="AS/400" />

</httpHeader>')

FROM SYSIBM.SYSDUMMY1;

Note that header field names are supposed to be case-insensitive, so User-Agent and USER-AGENT should work the same.

One special thing to note about passing header fields is that IBM has allowed a few additional options to be specified that can control the behavior of the HTTP functions. The table below contains the attribute names that can be added to the httpHeader element (from "HTTP request header fields and connection properties" in Accessing web services using IBM DB2 for i HTTP UDFs and UDTFs):

 

Attribute Names That Can Be Added to the httpHeader

Name

Value

Default

Comment

connectTimeout

Integer

System   default  

Maximum amount of time the JVM will wait for the connection in milliseconds

readTimeout

Integer

System   default

Maximum amount of time the JVM will wait for reading data in milliseconds

followRedirects

True/False

True

Indicates whether redirects should be implicitly followed when a 3xx response code is received from the server

useCaches

True/False

True

Instructs the JVM that caches are allowed to be used if available. DB2 for i does not implement a cache in the HTTP UDFs and UDTFs; however, a default cache might be used if the default cache is registered with the JVM.

 

To override the connection timeout to 1/2 second (500ms) and specify that redirects should not be automatically followed, specify the attributes as follows:

<httpHeader connectTimeout="500" followRedirects="false">

<header name="User-Agent" value="AS/400"/>

</httpHeader>

 

Note that the IBM manual has a typo error in that connectTimeout is incorrectly shown in the table as connectionTimeout.

 

For one more example, let's look at populating the Authorization field for when the web server requires basic authentication (i.e., a plain-text user name and password). With most modern web servers, when basic authentication is required, the user name and password can be passed in plain text on the URL as follows:

 

https://user:This email address is being protected from spambots. You need JavaScript enabled to view it./etc

 

As you might imagine, using secure HTTP (SSL/TSL) is desirable; otherwise, the plain text information can be easily captured.

If credentials can be passed via URL, why bother populating the authorization field? Because I found it doesn't always work in the URL.

 

When researching the prior tip on using the new HTTP functions, I found an example of how to access Gmail with the DB2 HTTP functions on IBM's developerWorks site.  Search the page for "Listing 5," where an example shows how to query a Gmail account and return all unread messages. The result is an Atom (XML) document that can easily be shredded by the XMLTABLE table function.

The example the developerWorks article shows how to access your Gmail info by placing the user name and password in the URL. However, with the DB2 for i functions, I found at least one case when the credentials wouldn't pass via the URL; this happens when you have a password containing the "at" (@) symbol. In this case, I found the only way I could log on is by passing credentials via the Authorization request field instead of the URL.

 

When passing the authorization value, the credentials should be sent as user:password. This result should then be encoded as Base64.

 

If my Gmail account is MikeSanso and password is F@t@l, the authorization value (before Base64 encoding) would look like this:

 

MikeSanso:F@t@l

 

Further, before encoding this credential as Base64, make sure to cast it to UTF-8 (aka CCSID 1208); otherwise, you'll Base64 encode an EBCDIC string, which won't work!

 

Here's the revised developerWorks query with my modifications for passing the Authorization info:

 

WITH Authorization AS (

SELECT SYSTOOLS.BASE64ENCODE(CAST('MikeSanso:F@t@l' AS VARCHAR(64) CCSID

1208)) AS Authorization_Identity

FROM SYSIBM.SYSDUMMY1

)

SELECT RESULT.*

FROM Authorization, XMLTABLE('$result/*[local-name()=''feed'']/*[local-name()=''entry'']'

      PASSING 

      XMLPARSE(DOCUMENT

SYSTOOLS.HTTPGETBLOB('https://mail.google.com/mail/feed/atom/',

'<httpHeader>

<header name="Authorization" value="Basic '||Authorization_Identity||'" />

</httpHeader>'))

AS "result"

COLUMNS

      title VARCHAR(128) PATH '*[local-name()=''title'']',

      summary VARCHAR(1024) PATH '*[local-name()=''summary'']',

      author_name VARCHAR(255) PATH '*[local-name()=''author'']/*[local-name()=''name'']',

      author_email VARCHAR(255) PATH '*[local-name()=''author'']/*[local-name()=''email'']'

) AS RESULT

 

Using the authentication header to pass credentials instead of the URL, although more complex, is recommended by IBM because there are cases when an SQL error or job log entry may reveal the URL and thereby disclose a user ID and password. If you have a Gmail account, you can try this out yourself.

  

In the end, the ability to pass header request values and inspect response values gives your application the versatility needed to exchange data with HTTP servers. Using headers allows your HTTP application interfaces to manage cookies, specify a content type when sending files, and send credentials, to name just a few possibilities.

References

TechTip: Check Out the New DB2 for i HTTP Functions

  

Accessing web services using IBM DB2 for i HTTP UDFs and UDTFs

 

Michael Sansoterra is a DBA for Broadway Systems in Grand Rapids, Michigan. He can be contacted at This email address is being protected from spambots. You need JavaScript enabled to view it..


BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: