Code example for HttpRequestBase

Methods: getMethodgetURIgetFirstHeadersetHeader

0
	 * 
	 * @param request HTTP request object 
	 * @return Processed HTTP request object 
	 */ 
	public HttpRequestBase processRequest(HttpRequestBase request) {
		final String uri = request.getURI().toString();
		final String method = request.getMethod();
		final String accept = request.getFirstHeader("Accept").getValue();
 
		final String body = "";
		String contentLength = "0";
 
		if (request instanceof HttpEntityEnclosingRequest) {
			final HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
			if (entity != null) {
				contentLength = String.valueOf(entity.getContentLength());
//				final byte[] content = new byte[(int)entity.getContentLength()]; 
//				try { 
//					((HttpEntityEnclosingRequestBase) request).getEntity().getContent().read(content); 
//				} catch (IOException e) { 
//					throw new BierIdeeException("Could not get body from " + request.getMethod().toUpperCase() + " request."); 
//				} 
//				body = new String(content); 
			} 
		} 
 
		final String hmacInputData = method + uri + accept + contentLength + body;
		String macString;
		try { 
			final Key signingKey = new SecretKeySpec(this.password.getBytes(), "HmacSHA256");
 
			final Mac m = Mac.getInstance("HmacSHA256");
			m.init(signingKey);
			m.update(hmacInputData.getBytes());
			final byte[] macBytes = m.doFinal();
 
			macString = new String(Hex.encodeHex(macBytes));
		} catch (NoSuchAlgorithmException e) {
			Log.d(LOG_TAG, "HmacSHA256 algorithm missing", e);
			throw new BierIdeeException("HmacSHA256 algorithm missing", e);
		} catch (InvalidKeyException e) {
			Log.d(LOG_TAG, "Invalid key for HmacSHA256 signing", e);
			throw new BierIdeeException("Invalid key for HmacSHA256 signing", e);
		} 
 
		if (macString.isEmpty()) {
			Log.d(LOG_TAG, "Empty Authorization-HMAC");
			throw new BierIdeeException("Empty Authorization-HMAC"); 
		} 
		final String authorizationHeader = this.username + ":" + macString;
		request.setHeader("Authorization", authorizationHeader);
 
		return request;
	} 
}