The following working function seems a bit hacky to me as it has been pieced together from a handful of (probably poorly written) online tutorials, and I want to know if there is a better (or more standard) way to approach this.
/***
* GET HTTP Operation
*
* @param request Request URI
* @return Element Root Element of XML Response
*/
protected Element get(String request) {
HttpURLConnection connection = null;
Element rootElement;
try {
URL url = new URL(this.baseUrl + request);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
BASE64Encoder enc = new sun.misc.BASE64Encoder();
String userpassword = this.username + ":" + this.password;
String encodedAuthorization = enc.encode( userpassword.getBytes() );
connection.setRequestProperty("Authorization", "Basic "+ encodedAuthorization);
connection.setRequestProperty("Content-type", "application/xml");
connection.setRequestProperty("Accept", "application/xml");
InputStream responseStream = connection.getInputStream();
//--- Parse XML response InputStream into DOM
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(responseStream);
rootElement = doc.getDocumentElement();
} catch(Exception e) {
System.out.print(e.toString());
rootElement = null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
return rootElement;
}
I am a Java novice and am especially unclear on proper try
/catch
usage.
I am creating a Java Wrapper for an REST API and this is a small piece of that puzzle. You can click here to see a bigger picture of the project as a whole.