Thursday, March 20, 2008

Code samples: invoking APIs using Java

Following on from my previous post, I thought it might be useful to post some sample code that demonstrates how to invoke EKP's APIs, in this case using Java.

Every API request must include an HTTP basic authentication header. If you are using Java's built-in HttpURLConnection class, you would need to construct and add this header manually. This is not hard, and the EKP APIs and Web Services Overview explains how to do it. However, it's even easier to use a library that supports HTTP basic authentication directly.

One such library is Jakarta Commons HttpClient. HttpClient is free, open source, and distributed under version 2.0 of the Apache License, meaning that it can be used with minimal obligations in software that is not itself open source. (Note that HttpClient has dependencies on both Commons Logging and Commons Codec, so you will also need both of those to run this sample code.)

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;

We begin by creating an instance of HttpClient, which is straightforward.

HttpClient httpClient = new HttpClient();

We need to initialize the HttpClient object with the appropriate user name and password. The user name is ignored by EKP, so we simply use the empty string. The password must match the value of the authentication.key property configured in the file WEB-INF/conf/ekp.properties.

String userName = "";
String key = "mysecretkey";
httpClient.getParams().setAuthenticationPreemptive(true);
httpClient.getState().setCredentials(AuthScope.ANY,
        new UsernamePasswordCredentials(userName, key));

As described in the previous post, we can create a user account (here, joestudent) by sending an HTTP POST request to /ekp/contentHandler/usersCsv, and including CSV-formatted data in the body of the request.

PostMethod postMethod1 = new PostMethod(
        "https://ekp.example.com/ekp/contentHandler/usersCsv");
String content1 = "Action,UserID,Password,FamilyName,GivenName\r\n"
                + "A,joestudent,dummypass,Student,Joe\r\n";
postMethod1.setRequestEntity(new StringRequestEntity(content1,
        "text/plain", "UTF-8"));
httpClient.executeMethod(postMethod1);

Similarly, we can enroll joestudent in a course with ID Derivatives_101 by sending an HTTP POST request to /ekp/enrollmentHandler, again with appropriately-formatted CSV data in the body of the request.

PostMethod postMethod2 = new PostMethod(
        "https://ekp.example.com/ekp/enrollmentHandler");
String content2 = "USERID,LEARNINGID\r\n"
                + "joestudent,Derivatives_101\r\n";
postMethod2.setRequestEntity(new StringRequestEntity(content2,
        "text/plain", "UTF-8"));
httpClient.executeMethod(postMethod2);

No comments: