Show ‘n Tell Thursday: Setting the Content-type from a Java agent (30 Mar 2006)


Suppose you are all into this new AJAX thing and you need to output XML from your agent. If you write the agent in LotusScript you simply output the Content-type header using a Print statement as the first output to the browser.

Print "Content-type: text/xml"

Setting the Content-type from a Java agent however seems to drive many people crazy. They seem to set the Content-type header correctly but it fails to manifest itself in the browser (the XML comes out wrapped in Domino HTML). This happens since they fail to understand what they actually need to do. The Content-type needs to go on its own line hence you need to insert a linebreak after the Content-type as the below example shows.

import lotus.domino.*;

public class JavaAgent extends AgentBase {

  public void NotesMain() {

    try {
      Session session = getSession();
      AgentContext agentContext = session.getAgentContext();

      java.io.PrintWriter pw = this.getAgentOutput();
      pw.println("Content-type: text/xml");
      pw.println("<?xml version="1.0" ?>");
      pw.println("<names>");
      pw.println("<name first="Mikkel" last="Heisterberg" />");
      pw.println("</names>");

    } catch(Exception e) {
      e.printStackTrace();
    }
  }
}

The key (highlighted in bold above) is to use the println()-method of the java.io.PrintWriter instead of simply the print()-method or the write()-method.

I said it wouldn’t be a long post…

3 thoughts on “Show ‘n Tell Thursday: Setting the Content-type from a Java agent (30 Mar 2006)”

  1. I just wanted to extend your good tip by telling that all HTTP headers can be set this way. The important thing is that nothing else is printed before the http-header.

    For example you could add cache control:
    pw.println(“Cache-Control: NOCACHE”);
    pw.println(“Pragma: no-cache”);

    or the pingback if you’re doing some bloggie stuff:

    X-Pingback: pw.println(“http://domino.dagerot.com/xmlrpc.php”);

    Like

Comments are closed.