(Return to main article: Samples for Java (REST) v1)
1. Specify service URL:
private static final String serviceURL = "http://URCHINHOST:URCHINPORT/services/v1/adminservice/";
2. Provide login information:
private static final String login = "URCHIN_LOGIN"; private static final String password = "URCHIN_PASSWORD";
3. Compose the REST URL:
URL service = new URL(serviceURL + "accounts/" + "?login=" + login + "&password=" + password);
4. Create the buffering character-input stream for retrieving the account list:
BufferedReader in = new BufferedReader(new InputStreamReader(service.openStream()));
5. Define namespace context implementation for data parsing:
class UrchinNamespaceContext implements NamespaceContext { public String getNamespaceURI(String prefix) { if (prefix == null) throw new NullPointerException("Null prefix"); if (prefix.equals("tns")) return "https://urchin.com/api/urchin/v1/"; else if ("xml".equals(prefix)) return XMLConstants.XML_NS_URI; return XMLConstants.NULL_NS_URI; } public String getPrefix(String namespaceURI) { throw new UnsupportedOperationException(); } public Iterator getPrefixes(String namespaceURI) { throw new UnsupportedOperationException(); } }
6. Execute the request:
XPathFactory fact = XPathFactory.newInstance(); XPath xp = fact.newXPath(); InputSource is = new InputSource(in); // set namespace context xp.setNamespaceContext(new UrchinNamespaceContext()); // retrieve list of accounts NodeList accounts = (NodeList)xp.evaluate("/tns:getAccountListResponse/account", is, XPathConstants.NODESET);
7. Display the response:
System.out.println("adminservice/accounts/"); for(int i = 0; i < accounts.getLength(); i++){ System.out.print("account id: \"" + xp.evaluate("accountId/text()", accounts.item(i)) + "\", "); System.out.print("account name: \"" + xp.evaluate("accountName/text()", accounts.item(i)) + "\", "); System.out.print("contact name: \"" + xp.evaluate("contactName/text()", accounts.item(i)) + "\", "); System.out.print("e-mail: \"" + xp.evaluate("emailAddress/text()", accounts.item(i)) + "\", "); System.out.println("phone number: \"" + xp.evaluate("phoneNumber/text()", accounts.item(i)) + "\""); } in.close();
Complete sample code for this example can be found in the AdminService.java file.
(Return to main article: Samples for Java (REST) v1)