AOL Journals - Open Blog API Samples

We provide you with some samples of code making use of the Blog API. Currently we have two samples:
  • Using PHP to Post a new entry. Note that this is a fragment of a sample program residing in the Mashup Gallery
  • Using Java to make a service.xml request and parsing the XML response.

PHP service.xml request

This code sends a service.xml request for an AOL/AIM screenname and obtains the blogs owned by that person. It passes the OpenAuth authToken for a user in order to view blogs that user is authorized to read. You can see the code that obtains the authToken here, in a Mashup Sample that reads a person's AIM Buddy List and returns a list of all their buddies along with any AOL blogs held by those buddies:

<?
  // These three subroutines handle Blogs response XML

  // This routine checks any attributes sent with an element
  function blogStartElement($parser, $name, $attrs) {
    global $value, $collect, $href;
    $value = "";		// 'reset' to get current CDATA for this element (if any)

    if (!strcmp($name, "COLLECTION")) {
      $href = $attrs["HREF"];
      $collect = true;		// in a collection, so take any atom:title as valid
    }
  }

  // This routine accesses CDATA sent within an element
  function blogEndElement($parser, $element) {
    global $value, $collect, $href;

    if (!strcmp($element, "ATOM:TITLE")) {
      if ($collect) {
        print "<br/>     Blog Title: " . $value . 
              '<br/>     At Location: <a href="' . $href . 
		  '">' . $href . "</a>";
      }
    }
  }

  // This routine collects CDATA for an element
  function blogCharData($parser, $data) {
    global $value;
    $value = $data;
  }

  /** Checks for blogs for a person (called for each BL member) */
  function checkForBlogs($owner) {
    global $collect;            // a boolean flag used to avoid collecting the workspace title
    global $authToken;          // Received from OpenAuth for a user logging in
    global $devId, $baseUrl;    // DevId owned by the mashup running this program

    // Create the HTTP request
    $checkBlogsUrl = "http://api.blogs.aol.com/" . $owner . "/service.xml";
    $sessionRequest = curl_init();
    curl_setopt( $sessionRequest, CURLOPT_URL, $checkBlogsUrl);
    curl_setopt( $sessionRequest, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt( $sessionRequest, CURLOPT_REFERER, $baseUrl . "loginresp-blogs.php");
    $header[] = "X-AOL-DEVID: " . $devId;
    $header[] = 'Authorization: OpenAuth token="' . $authToken . '"';
    curl_setopt( $sessionRequest, CURLOPT_HTTPHEADER, $header);
    curl_setopt( $sessionRequest, CURLOPT_HEADER, 1);
    $responseXml = curl_exec( $sessionRequest );

    if (curl_errno($sessionRequest)) {
      $aimValidation_error = "Got error:" . curl_errno($sessionRequest);
      print $aimValidation_error;
      curl_close($sessionRequest);
      return false;
    }
    curl_close($sessionRequest);

    // parse response XML - takes care of reporting blogs in display
    $collect = false;	// default when starting a service.xml parse
    $responseXml = strstr($responseXml, "<?");	// sigh - strip HTTP metadata
    $blogs_xml_parser = xml_parser_create();
    xml_set_element_handler($blogs_xml_parser, 'blogStartElement', 'blogEndElement');
    xml_set_character_data_handler($blogs_xml_parser, 'blogCharData');
    xml_parse($blogs_xml_parser, $responseXml, true);
    xml_parser_free($blogs_xml_parser);
  }



Java Post Entry Sample

This sample sends a POST command to add a new entry for a blog. It doesn't include code to obtain the OpenAuth token - I'll put up a sample soon in our Mashup Gallerywith that extension.

The code uses the Apache HTTPClient Class in order to create a POST request - see here in order to obtain the JAR file and documentation.

import java.io.*;
import java.text.*;
import java.util.*;
import java.net.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;

public class AtomAddEntry 
{
  private static final String devId = "co1DRMvigZJXvWk";        // DevID for MyMashup
  private static final String referer = "http://mymashup.com";  // associated URL

  private static final int SOCKET_TIMEOUT = 10000;
  private static HttpClient httpClient = 
                                new HttpClient(new MultiThreadedHttpConnectionManager());
  static {
    httpClient.getHttpConnectionManager().getParams().setDefaultMaxConnectionsPerHost(5);
    httpClient.getHttpConnectionManager().getParams().setMaxTotalConnections(20);
  }

  /** Given the necessary information, adds a new 'basic' entry (just title and contents)
   *  to an AOL blog (Journal)
   *  @param sn - the AOL screename of the user owning the blog we're adding to
   *  @param blogName - the 'short' name of the blog we're adding to
   *  @param entryTitle - the subject title desired for the new entry
   *  @param entryContents - contents for the desired entry
   *  @param token - contains the token from user logging into AOL OpenAuth 
   */
  public void doAddEntry(String sn, String blogName, String entryTitle, String entryContents,
                         String token) 
  {
     try {
       httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(SOCKET_TIMEOUT);
       httpClient.getParams().setConnectionManagerTimeout(SOCKET_TIMEOUT);
       httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(SOCKET_TIMEOUT);

       // create URL for Atom request using sn & blogName to access the desired blog
       String postUrl = "http://api.blogs.aol.com/_atom/journal/" + sn + "/" + blogName;
       PostMethod method = new PostMethod(postUrl);

       method.setRequestHeader("Content-type", "application/atom+xml;charset=UTF-8");
       method.setRequestHeader("Authorization", "OpenAuth token=\"" + token = "\"");
       method.setRequestHeader("X-AOL-DEVID", devId);    // static - see above
       method.setRequestHeader("REFERER", referer);      // static - see above

       // set content for the entry
       String bodyContent = "" + entryTitle + "" + entryContents + "";
       StringRequestEntity sre = new StringRequestEntity(bodyContent);
       method.setRequestEntity(sre);

       // Execute the Atom request and get the response - 
       // which will contain the full description of the added entry
       // all errors will be returned in the HTTP Status Code (with description in the 
response) int status = httpClient.executeMethod(method); System.err.println ("*********http status code = " + status); String response = getHttpResponse(method); System.err.println ("*********response = " + response); } catch (Exception e) { System.err.println ("error " + e); e.printStackTrace(); } } /** Gets the contents of an HTTP response */ private String getHttpResponse (HttpMethod method) throws IOException { StringBuffer response = new StringBuffer(512); InputStream responseStream = method.getResponseBodyAsStream(); InputStreamReader isr = new InputStreamReader(responseStream); BufferedReader br = new BufferedReader(isr); String inputLine; //grab the response contents while ((inputLine = br.readLine()) != null) response.append(inputLine); return response.toString(); } // Just to show how the routine might be called public static void main (String []args) { String openAuthToken = args[0]; // get login token after user login AtomAddEntry aae = new AtomAddEntry(); aae.doAddEntry("joeuser", "MyBlog", "Another Entry", "and this is yet more atomic content - handle with care!", openAuthToken); } }