Calling REST Web Services from Java

Wow – it initially seemed much harder to do REST web services in Java than it should have been – it took a while for me to find this web site. Everyone wanted me to download a jar or something – I knew this had to work in a few lines of Java with no jars…

Thanks to: http://xml.nig.ac.jp/tutorial/rest/index.html

My code below.


try {
// Thanks: http://xml.nig.ac.jp/tutorial/rest/index.html
URL url = new URL(restEndPoint);
//make connection, use post mode, and send query
URLConnection urlc = url.openConnection();
urlc.setDoOutput(true);
urlc.setAllowUserInteraction(false);
String encodedPost = URLEncoder.encode(ret);
PrintStream ps = new PrintStream(urlc.getOutputStream());
ps.print("launchData="+encodedPost);
ps.close();
//retrieve result
BufferedReader br = new BufferedReader(new InputStreamReader(urlc
.getInputStream()));
String str;
StringBuffer sb = new StringBuffer();
while ((str = br.readLine()) != null) {
sb.append(str);
sb.append("\n");
}
br.close();
response = sb.toString();
if ( response == null ) {
setErrorMessage(request, "Launch REST Web Service returned nothing");
}
}
catch(Exception e) {
e.printStackTrace();
setErrorMessage(request, "Failed REST service call. Exception="+e);
response = null;
}