VOOZH about

URL: https://docs.gravatar.com/avatars/java/

⇱ Java – Gravatar For Developers


Skip to content

Java

If you’d like an easy way of working with Gravatar, then check out Nathan Cheshire’s GravatarJavaClient, otherwise read on. Things are a little complex in Java. The following class will provide you with a static method that returns the format SHA-256 of an input string:

import java.util.*;
import java.io.*;
import java.security.*;

public class HashUtil {
 public static String hex(byte[] array) {
 StringBuffer sb = new StringBuffer();
 for (int i = 0; i < array.length; ++i) {
 sb.append(Integer.toHexString((array[i]
 & 0xFF) | 0x100).substring(1,3)); 
 }
 return sb.toString();
 }

 public static String sha256Hex(String message) {
 try {
 MessageDigest md = MessageDigest.getInstance("SHA-256");
 return hex(md.digest(message.getBytes("UTF-8")));
 } catch (NoSuchAlgorithmException e) {
 // Consider logging this exception or rethrowing as a RuntimeException
 } catch (UnsupportedEncodingException e) {
 // Consider logging this exception or rethrowing as a RuntimeException
 }
 return null;
 }
}

This class can then be used to return the SHA-256 hash of an email address (make sure you lower case it first!) like this:

String email = "someone@somewhere.com".toLowerCase();
String hash = sha256Hex(email);
String gravatarURL = "https://gravatar.com/avatar/" + hash;

With the hex string that is returned, you can construct your gravatar URL.



Last updated on: