Community articleSending requests in Java
Added by IBM contributorIBM on September 27, 2013
Rate this article 1 starsRate this article 2 starsRate this article 3 starsRate this article 4 starsRate this article 5 stars

Here is sample code that uses HTTP and JSON libraries to send GET, POST, PATCH, and DELETE requests to the Domino® Data Service and read the responses.
package com.ibm.sample.rest.httpclient;
 
import java.io.*;
import java.util.StringTokenizer;
 
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpClientParams;
import com.ibm.commons.util.io.json.*;
 
/**
 * 
 * This is a sample Java application that uses an HTTP client library and a JSON library 
 * to perform sample REST style CRUD (Create, Read, Update, and Delete) operations on resources
 * available through the Domino Access Servces API for Data services.  
 * 
 * The HTTP client library and JSON library used in this sample are available with the installation 
 * of the Domino Access Services API on the Domino server. 
 * 
 * The target database is the XPages Extension Library sample database, xpagesext.nsf, included with 
 * the XPages Extension Library download.  See http://extlib.openntf.org/
 * 
 * This sample includes: 
 *  - GET request and response for DAS resources, e.g., databases, views, view entries. 
 *  - Creation of name and password credentials for basic name and password authentication. 
 * 	- Create, Read, Update and Delete operations for a single document.
 * 
 * How to configure and run this sample:
 * (Please see the Domino Access Services documentation for more details on these steps.) 
 * 
 * Configure the test environment:
 * - Install the Domino Access Services API on the Domino server. 
 * - Configure Domino server security to enable access from the DAS API. 
 * - Enable "Name and Password" authentication in the TCP Authentication setting for the Domino server. 
 * - Add the XPages Extension Library sample database, xpagesext.nsf, to the Domino server data directory. 
 * - Use the IBM Lotus Notes client to set the database property for xpagesext.nsf to 
 *   allow the "Data" service. 
 * 
 * Configure the Java development environment:
 * - If you would like to use the HTTP client and JSON libraries available from the DAS install, 
 * 	add the following jar files to your Java development and runtime environment. 
 * 	1. [Domino root]\osgi\shared\eclipse\plugins\
 *		com.ibm.commons_8.5.3.yyyymmdd-hhmm\lwpd.commons.jar
 * 	2. [Domino root]\osgi\rcp\eclipse\plugins\
 * 		org.apache.commons.logging_1.0.4.20110614-1451.jar
 *  3. [Domino root]\osgi\rcp\eclipse\plugins\
 * 		org.apache.commons.codec_1.3.0.20110614-1451.jar
 *  4. [Domino root]\osgi\rcp\eclipse\plugins\
 * 		org.apache.commons.httpclient_3.0.0.20110614-1451.jar
 * 
 * Run the sample as a Java application, with arguments: 
 * 
 *  Server Address		e.g. server=server.mycompany.com
 *  DatabaseName		e.g. database=xpagesext.nsf
 *  User name (Optional): e.g. user=Myuser/Org
 *  Password  (Optional): e.g. password=mypassword
 *  View name (Optional): e.g. AllContacts
 *  Resources to try (Optional): Comma separated list of one or more of the following:
 * 		 databases, views, entries, documents
 * 			 e.g. resources=databases, documents
 * 
 */
 
public class SampleHttpClient {
 
	public static String userName = "";
	public static String userPassword = "";
	public static String DominoServerAddress = "";
	public static UsernamePasswordCredentials myCreds = null;
	public static HttpClient client = null;
	public static String BaseURI = "http://";
	
	public static final String API_BASE_URI = "/api";
	public static final String API_DATABASES_URI = "/api/data";
	public static final String API_VIEWS_URI = "/api/data/collections";		
	public static final String API_DOCUMENTS_URI = "/api/data/documents";
	
	// argument prefixes
	public static final String SERVER_ARG = "server=";
	public static final String DATABASE_ARG = "database=";
	public static final String USERNAME_ARG = "user=";
	public static final String PASSWORD_ARG = "password=";
	public static final String RESOURCES_ARG = "resources=";
	public static final String VIEWNAME_ARG = "view=";		
	
	// resource arg names
	public static final String RESOURCE_DATABASES = "databases";
	public static final String RESOURCE_VIEWS = "views";
	public static final String RESOURCE_VIEWENTRIES = "entries";
	public static final String RESOURCE_DOCUMENTS = "documents";		
 
	public static String databaseName = "xpagesext.nsf";
	public static String viewName = "AllNames";		
	public static String resourcesArg = "";
 
	public static void main(String[] args) throws Exception {
		boolean invalidArgs = false;
 
		if (args.length < 1)
			invalidArgs = true;
		else
			{
				for (int i = 0; i < args.length; i++) {
					String arg = args[i];
					String argsValue = "";
					
					if (arg.contains(SERVER_ARG)) {
						argsValue= arg.substring(arg.indexOf(SERVER_ARG) + SERVER_ARG.length());
						DominoServerAddress = argsValue.trim();
					} else if (arg.contains(DATABASE_ARG)) {
						argsValue= arg.substring(arg.indexOf(DATABASE_ARG) + DATABASE_ARG.length());
						databaseName = argsValue.trim();							
					} else if (arg.contains(USERNAME_ARG)) {
						argsValue= arg.substring(arg.indexOf(USERNAME_ARG) + USERNAME_ARG.length());
						userName = argsValue.trim();							
					} else if (arg.contains(PASSWORD_ARG)) {
						argsValue= arg.substring(arg.indexOf(PASSWORD_ARG) + PASSWORD_ARG.length());
						userPassword = argsValue.trim();							
					} else if (arg.contains(RESOURCES_ARG)) {
						argsValue= arg.substring(arg.indexOf(RESOURCES_ARG) + RESOURCES_ARG.length());
						resourcesArg = argsValue.trim();							
					} else if (arg.contains(VIEWNAME_ARG)) {
						argsValue= arg.substring(arg.indexOf(VIEWNAME_ARG) + VIEWNAME_ARG.length());
						viewName = argsValue.trim();							
					}
				}
			}
		
		if (invalidArgs)
			{
			System.out.println("To run this application specify the following arguments:");
			System.out.println(" Server Address		e.g. server=server.mycompany.com");
			System.out.println(" DatabaseName		e.g. database=xpagesext.nsf");
			System.out.println(" User name (Optional): e.g. user=Myuser/Org");			
			System.out.println(" Password  (Optional): e.g. password=mypassword");
			System.out.println(" View name (Optional): e.g. AllContacts");	
			System.out.println("\n Resources to try (Optional): Comma separated list of one or more of the following:");
			System.out.println("\t\t " + RESOURCE_DATABASES  + ", " + RESOURCE_VIEWS + ", " + RESOURCE_VIEWENTRIES + ", " + RESOURCE_DOCUMENTS);
			System.out.println("\t\t\t e.g. resources=databases, documents");				
			System.out.println("");
			return;
		}
	
		System.out.println("Running rest test(s) with the following arguments:");
		System.out.println("\tServer Address: " + DominoServerAddress);
		System.out.println("\t" + ((databaseName.length() > 0) ? ("database name = " +databaseName) : "database name was not supplied, using default"));
		System.out.println("\t" + ((viewName.length() > 0) ?  ("view name = " +viewName) : "View name was not supplied, using default"));				
		System.out.println("\t" + ((userName.length() > 0) ? ("user name = " +userName) : "User name was not supplied"));				
		System.out.println("\t" + ((userPassword.length() > 0) ? "User Password was provided. " : "User password was not supplied"));				
		System.out.println("\t" + ((resourcesArg.length() > 0) ? ("Resources to try: " + resourcesArg) : "resources list not specified, default base resource"));			
		System.out.println("");			
	
		// Create the http client
		client = new HttpClient();
		HttpState state = client.getState();
		HttpClientParams params = client.getParams();
		
		// A name and password was supplied, create credentials, otherwise the user is Anonymous
		if (userName.length() > 0 && userPassword.length() > 0) {
			myCreds = new UsernamePasswordCredentials(userName,userPassword);
			System.out.println("Created credentials for " + myCreds.getUserName());
			// Apply the credentials to the httpclient for preemptive authentication. 
			params.setAuthenticationPreemptive(true);
			state.setCredentials(AuthScope.ANY, myCreds);
		}
		
		// Create the base segment of the URI with the target server
		BaseURI = BaseURI + DominoServerAddress;
		
		if (resourcesArg.length() > 0) {
			// Build the URI and select the test based on arguments from the command line. 
			StringTokenizer tokenizer = new StringTokenizer(resourcesArg, ", ");
			while ( tokenizer.hasMoreTokens() ) {
				String resourceName = tokenizer.nextToken();
				if (resourceName.equalsIgnoreCase(RESOURCE_DATABASES)) {
					testDatabases(BaseURI + API_DATABASES_URI);
				} else if (resourceName.equalsIgnoreCase(RESOURCE_VIEWS)) {
					testViews(BaseURI + "/" + databaseName + API_VIEWS_URI);
				} else if (resourceName.equalsIgnoreCase(RESOURCE_VIEWENTRIES)) {
					testViewEntries(BaseURI + "/" + databaseName + API_VIEWS_URI + "/name/" + viewName);
				} else if (resourceName.equalsIgnoreCase(RESOURCE_DOCUMENTS)) {
					testDocuments(BaseURI + "/" + databaseName +  API_DOCUMENTS_URI);
				} 
			}
		}
		else {
			testBase(BaseURI + API_BASE_URI);
		}
	}
	
	/*
	 * Read base URI to DAS Data service
	 */
	private static void testBase(String url) {
		GetMethod get = null;
		try {
			get = new GetMethod(url);
			client.executeMethod(get);
			printResponseBodyToConsole(get);				
		} catch (HttpException he) {
			System.err.println("Http error connecting to '" + DominoServerAddress + "'");
			System.err.println(he.getMessage());
			System.exit(-1);
		} catch (IOException ioe) {
			System.err.println("Unable to connect to '" + DominoServerAddress + "'");
			System.err.println(ioe.getMessage());
			System.exit(-1);
		}
	}
			
	/*
	 * Get a list of databases
	 */
	private static void testDatabases(String url) {
		GetMethod get = null;
		try {
			System.out.println("");
			System.out.println("Test of databases resource..\n");
			
			get = new GetMethod(url);
			client.executeMethod(get);
			printResponseBodyToConsole(get);
			System.out.println("End test of databases resource..\n\n");				
		} catch (HttpException he) {
			System.err.println("Http error connecting to '" + DominoServerAddress + "'");
			System.err.println(he.getMessage());
			System.exit(-1);
		} catch (IOException ioe) {
			System.err.println("Unable to connect to '" + DominoServerAddress + "'");
			System.err.println(ioe.getMessage());
			System.exit(-1);
		}
	}
	
	/*
	 * Get list of views and folders of a database
	 */
	private static void testViews(String url) {
		GetMethod get = null;
		try {
			System.out.println("");
			System.out.println("Test of views resource..\n");
			
			get = new GetMethod(url);
			client.executeMethod(get);
			printResponseBodyToConsole(get);
			System.out.println("End test of views resource..\n\n");				
		} catch (HttpException he) {
			System.err.println("Http error connecting to '" + DominoServerAddress + "'");
			System.err.println(he.getMessage());
			System.exit(-1);
		} catch (IOException ioe) {
			System.err.println("Unable to connect to '" + DominoServerAddress + "'");
			System.err.println(ioe.getMessage());
			System.exit(-1);
		}
	}
		
	/*
	 * Get list of entries in a given view
	 */
	private static void testViewEntries(String url) {
		GetMethod get = null;
		try {
			System.out.println("");
			System.out.println("Test of view entries resource..\n");
			
			get = new GetMethod(url);
			client.executeMethod(get);
			printResponseBodyToConsole(get);
			System.out.println("End test of view entries resource..\n\n");				
		} catch (HttpException he) {
			System.err.println("Http error connecting to '" + DominoServerAddress + "'");
			System.err.println(he.getMessage());
			System.exit(-1);
		} catch (IOException ioe) {
			System.err.println("Unable to connect to '" + DominoServerAddress + "'");
			System.err.println(ioe.getMessage());
			System.exit(-1);
		} 
	}
		
	/*
	 * Perform REST style CRUD (Create, Read, Update, and Delete) operations on a single document. 
	 */
	private static void testDocuments(String url) {
		System.out.println("");
		System.out.println("Test of documents resource..\n");
 
		// Use JSON library methods to create a JSON object representing a new document.
		JsonObject jsonItem = new JsonJavaObject();
		jsonItem.putJsonProperty("FirstName", "Aaron");
		jsonItem.putJsonProperty("LastName", "Adams");
		jsonItem.putJsonProperty("EMail", "aaron_adams@renovations.com");
		jsonItem.putJsonProperty("City", "Quincy");
		jsonItem.putJsonProperty("State", "MA");
		jsonItem.putJsonProperty("Id", "CN=Aaron Adams/O=renovations");
		jsonItem.putJsonProperty("Form", "Contact");
		// Create a new document in the database and return the URI of the document. 
		String documentURI = createDocument(url, jsonItem);
 
		// Read the new document 
		HttpMethod getResponse = readDocument(documentURI);
		if (getResponse.getStatusCode() == 200) {
			printResponseBodyToConsole(getResponse);
		} else {
			System.out.println("Error: GET return code expected 200, actual "
					+ getResponse.getStatusCode());
			System.exit(-1);
		}
 
		// Update the document, change City from "Quincy" to "Braintree". 
		jsonItem = new JsonJavaObject();
		jsonItem.putJsonProperty("City", "Braintree");
		updateDocument(documentURI, jsonItem);
		
		// Read the document after update. 
		getResponse = readDocument(documentURI);
		if (getResponse.getStatusCode() == 200) {
			printResponseBodyToConsole(getResponse);
		} else {
			System.out.println("Error: GET return code expected 200, actual "
					+ getResponse.getStatusCode());
			System.exit(-1);
		}
 
		// Delete the document.
		deleteDocument(documentURI);
 
		// Attempt to read the document after delete, should be not found. 
		getResponse = readDocument(documentURI);
		if (getResponse.getStatusCode() == 404) {
			System.out.println("Document not found, as expected.");
		} else {
			System.out.println("Error: GET return code expected 404, actual "
					+ getResponse.getStatusCode());
			System.exit(-1);
		}
 
	}
 
	/*
	 *  Use org.apache.commons.httpclient.methods.PostMethod to create a document.
	 *  The new document URI is returned in the Location response-header field.
	 */
	private static String createDocument(String url, JsonObject jsonItem) {
		String NewDocURI = null;
		PostMethod post = null;
		try {
			post = new PostMethod(url);
			post.setRequestEntity(new StringRequestEntity(jsonItem.toString(),
					null, null));
			post.setRequestHeader("Content-Type", "application/json");
			post.setRequestHeader("Accept", "application/json");
			client.executeMethod(post);
			if (post.getStatusCode() != 201) {
				System.out.println("Error: Return code " + post.getStatusCode()
						+ " on POST of url: " + url);
				System.out.println("Please check the test setup, exiting.");
				System.exit(-1);
			}
			Header newLoc = post.getResponseHeader("Location");
			NewDocURI = newLoc.getValue();
			printResponseBodyToConsole(post);
		} catch (HttpException he) {
			System.err.println("Http error connecting to '"
					+ DominoServerAddress + "'");
			System.err.println(he.getMessage());
			System.exit(-1);
		} catch (IOException ioe) {
			System.err.println("Unable to connect to '" + DominoServerAddress
					+ "'");
			System.err.println(ioe.getMessage());
			System.exit(-1);
		}
		return NewDocURI;
	}
 
	/*
	 * Use org.apache.commons.httpclient.methods.GetMethod to read a document.
	 */
	private static HttpMethod readDocument(String url) {
		GetMethod get = null;
		try {
			get = new GetMethod(url);
			get.setRequestHeader("Content-Type", "application/json");
			get.setRequestHeader("Accept", "application/json");
			client.executeMethod(get);
		} catch (HttpException he) {
			System.err.println("Http error connecting to '"
					+ DominoServerAddress + "'");
			System.err.println(he.getMessage());
			System.exit(-1);
		} catch (IOException ioe) {
			System.err.println("Unable to connect to '" + DominoServerAddress
					+ "'");
			System.err.println(ioe.getMessage());
			System.exit(-1);
		}
		return get;
	}
 
	/*
	 * Use org.apache.commons.httpclient.methods.PostMethod with request-header 
	 * "X-HTTP-Method-Override" set to "PATCH" to update single items on a document. 
	 * 
	 * Note the difference of "PATCH" to "PUT" for the DAS API: PATCH allows the replacement of a single 
	 * item in the document, while PUT will replace the entire document. 
	 */
	private static void updateDocument(String url, JsonObject jsonItem) {
		PostMethod put = null;
		try {
			put = new PostMethod(url);
			put.setRequestEntity(new StringRequestEntity(jsonItem.toString(),
					null, null));
			put.setRequestHeader("Content-Type", "application/json");
			put.setRequestHeader("Accept", "application/json");
			put.setRequestHeader("X-HTTP-Method-Override", "PATCH");
 
			client.executeMethod(put);
			if (put.getStatusCode() != 200) {
				System.out.println("Error: Return code " + put.getStatusCode()
						+ " on PUT of url: " + url);
				System.out.println("Please check the test setup, exiting.");
				System.exit(-1);
			}
			printResponseBodyToConsole(put);
		} catch (HttpException he) {
			System.err.println("Http error connecting to '"
					+ DominoServerAddress + "'");
			System.err.println(he.getMessage());
			System.exit(-1);
		} catch (IOException ioe) {
			System.err.println("Unable to connect to '" + DominoServerAddress
					+ "'");
			System.err.println(ioe.getMessage());
			System.exit(-1);
		}
	}
 
	/*
	 * Use org.apache.commons.httpclient.methods.DeleteMethod to delete a document.
	 */
	private static void deleteDocument(String url) {
		DeleteMethod delete = null;
		try {
			delete = new DeleteMethod(url);
			delete.setRequestHeader("Content-Type", "application/json");
			delete.setRequestHeader("Accept", "application/json");
			client.executeMethod(delete);
			printResponseBodyToConsole(delete);
			if (delete.getStatusCode() != 200) {
				System.out.println("Error: Return code "
						+ delete.getStatusCode() + " with DELETE on url: "
						+ url);
				System.out.println("Please check the test setup, exiting.");
				System.exit(-1);
			}
		} catch (HttpException he) {
			System.err.println("Http error connecting to '"
					+ DominoServerAddress + "'");
			System.err.println(he.getMessage());
			System.exit(-1);
		} catch (IOException ioe) {
			System.err.println("Unable to connect to '" + DominoServerAddress
					+ "'");
			System.err.println(ioe.getMessage());
			System.exit(-1);
		}
	}
 
	/*
	 * Print response body to standard out
	 */
	private static void printResponseBodyToConsole(HttpMethod myMethod) {
		try {
			System.out.println(myMethod.getName() + " "
					+ myMethod.getStatusLine().toString());
			BufferedReader in = new BufferedReader(new InputStreamReader(
					myMethod.getResponseBodyAsStream()));
			String inputLine;
			while ((inputLine = in.readLine()) != null)
				System.out.println(inputLine);
			in.close();
		} catch (HttpException he) {
			System.err.println("Http error connecting to '"
					+ DominoServerAddress + "'");
			System.err.println(he.getMessage());
			System.exit(-1);
		} catch (IOException ioe) {
			System.err.println("Unable to connect to '" + DominoServerAddress
					+ "'");
			System.err.println(ioe.getMessage());
			System.exit(-1);
		}
	}
 
}


Parent topic: Programming Domino Data Service