AIAIO: Our Blog

AIAIO: Our Blog

The pulse and reviews of Alexander Interactive

Author Archive

A Simple Java REST Client with Apache Commons HttpClient

I recently needed to build a RESTful web service client for my Java application. I wanted something simple and I had a particular set of requirements I wanted to code around (like being able to return the original request parameters along with the response) so the leaner the the actual client the better. After a little research I decided to go with a solution built on Apache Commons HttpClient which provides a rich set of abstractions for client side http interactions. I like HttpClient because it provides a higher and more functional level of abstraction than underlying java.net classes but at the same time allows you to code around whatever Http idioms you want (simple request/response, conversational services, data submission etc.) without alot of bridge code like annotations or library specific interface implementations.

Since I needed to both asynchronously POST data to a restful endpoint as well as perform GET request against another endpoint,  I abstracted all of the parameter bundling and message sending into a single processRequest() method instead of implementing separate post/get code. I also standardized the return type to a Map containing the objects I needed for my app e.g. the request parameters, the actual response and the HTTP response code (REQUEST_PARAMS, RESPONSE_BODY and RESPONSE_STATUS respectively):

processRequest():

public Map<String, Object> processRequest(String serviceUrl,
                        String sendMethod, Map<String, String> params)
{
                if (StringUtils.isBlank(serviceUrl)) {
                    throw new AiServiceException("Service URL is required");
                }
                // Essentially return a new HttpClient(), but can be pulled from Spring context
                HttpClient httpclient = getHttpClient();
                HttpMethod method = getHttpMethodFromString(sendMethod);//See Details Below
                method.setPath(serviceUrl);
                httpclient.getParams().setParameter("http.protocol.version",HttpVersion.HTTP_1_1);
                httpclient.getParams().setParameter("http.socket.timeout", Integer.valueOf(responseTimeOut));
                httpclient.getParams().setParameter("http.protocol.content-charset",charSet);
                setRequestParams(method, params);
                HashMap<String, Object> responseObject = new HashMap<String, Object>();
                try {
                        int responseCode = httpclient.executeMethod(method);
                        String respBody=getResponseBody(method);// See details Below
                        responseObject.put(REQUEST_PARAMS, params);
                        responseObject.put(RESPONSE_BODY, respBody);
                        responseObject.put(RESPONSE_STATUS, responseCode);
                        return responseObject;
                } catch (Exception e) {
                        logger.error("Error Sending REST Request [URL:"+serviceUrl+",METHOD:"+sendMethod+",PARAMS:"+params+"]", e);
                        throw new AiServiceException(e);
                } finally {
                        method.releaseConnection();
                }
        }

To make this work I  wrote a method parse an actual HttpMethod Object from a given string:
getHttpMethodFromString():

private HttpMethod getHttpMethodFromString(String methodString) {
		if (StringUtils.isNotBlank(methodString)) {
			org.springframework.http.HttpMethod parsedMethod = org.springframework.http.HttpMethod
					.valueOf(methodString.toUpperCase());
			switch (parsedMethod) {//Add other methods as needed PUT, DELETE etc.
			case GET:
				return new GetMethod();
			case POST:
				return new PostMethod();
			default:
				return new GetMethod();
			}
		}
		return new GetMethod();
	}

Finally I needed to make sure to read the entire response before returning it to caller:
getResponseBody():

protected String getResponseBody(HttpMethod method){
		//Ensure we have read entire response body by reading from buffered stream
		if(method!=null&& method.hasBeenUsed()){
			BufferedReader in=null;
			StringWriter stringOut= new StringWriter();
			BufferedWriter dumpOut = new BufferedWriter(stringOut,8192);
			try {
				 in=new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
				String line = "";
				while ((line = in.readLine()) != null) {
					dumpOut.write(line);
					dumpOut.newLine();
				}
			} catch (IOException e) {
				logger.error("Error Reading Response Stream",e);
				throw new AiServiceException(e);
			}finally{
				try {
					dumpOut.flush();
					dumpOut.close();
					if(in!=null)
						in.close();
				} catch (IOException e) {
					logger.warn("Error Closing Response Stream",e);
				}
			}
			return StringEscapeUtils.unescapeHtml(stringOut.toString());
		}
		return null;
	}

The newer Apache HttpComponents Project offers some evolutionary features over HttpClient like Plug-able authentication mechanisms, but the code shown above based on the legacy HttpClient libs works very well for my needs and is easily upgradeable should the need arise.

Technology

Nook Color + E-Comics = Awesome!!

In search of electronic comic reader

I got the Barnes and Noble Nook Color late last year after being disappointed both by the 1st iPad and the available Android tablets at the time. Resigned to not invest in a full fledged tablet as of yet I also found myself unable to take the e-ink plunge for 1 reason: comic books are printed in color.  I had been managing to get by reading e-comics with ComicRack on my Desktop/Laptop and Comic Book Lover does a reasonable enough job on the iPhone 4. But trying to get caught up on X-Men in rush hour traffic is impossible with a laptop and just annoying on a small (if beautiful) screen.

Enter the Nook Color: an Android powered, full color, touch screen, wifi enabled e-reader. At $249, it’s priced beween full blown Android tablets/iPad and the current king of pure e-readers, the Kindle. But because the Nook is based on the Android operating system you actually do gain the potential for full tablet capabilities (i.e. non Barnes and Noble apps) either through eventual Barnes and Nobles upgrades or through various rooting/unlocking techniques available on the web.

Getting Comic Books on the Nook Color

When it comes to actually reading comics on the Nook, the first thing to do is get them on to the device.  The Nook lets you drag and drop any of its supported formats directly on to the device (or  an optional micro SD card) once its attached to your Mac or PC so loading new content is usually easy. However since most e-comics come in either CBR or CBZ format you will usually have to convert them to a format the Nook supports, so I usually use Calibre to convert the comics to either E-Pub or PDF depending on the content:

  • EPub is good for manga and similarly formatted graphic novels and they come over well on the Nook’s 7 in screen. Also the navigation is pretty similar to readers on the IPhone so you can tap the edge of the screen to quickly navigate forward and backward.
  • PDF is generally better for standard comics and graphic novels because you can zoom in on larger panels and view the page in different orientations. However current native PDF reader that ships with the Nook Color is sort of lame so you can’t do two page layouts for example and have to navigate using vertical swipes only. These aren’t really deal breakers (since you cant do two page layouts in EPub either), but I do miss the effect of many multipage panels and that can make reading them a little disjointed.

Other Coolness

Beyond the general comic book coolness the expandability of an SD card is pretty cool for rotating different comic collections in and off quickly. I also use the Book Shelf feature to cross file comics for instance organizing both by series title and by story arc. Also the built in web browser, while not super snappy, is really handy when you quickly need to hit up wikipedia to figure out when Batman 1st met Talia Al Ghul. Beyond the comics it self, reading  magazines and periodicals on the NookColor is also pretty awesome  as a lot of thought went into their Magazine reader interface.

Conclusion

With the advent of the iPad 2 and the Motorola Xoom I might finally take the tablet plunge, but thanks to the Nook Color I’m not pressed. With its vivid screen, expandability, supported formats, ease of use and Android roots the Nook Color is not just the best only E-reader for comics and graphic novels, but compelling mobile platform with room to grow in its space.

Gadgets