2012-11-20 50 views
1

我试图连接到Grooveshark api。这是签署请求的Grooveshark指南: http://developers.grooveshark.com/tuts/public_apijava中哈希json

这就是我如何签署我的数据。但是我收到错误:“签名无效”。我应该形成JsonObject还是数据可以是String?

String data = "{\"method\":\"getArtistSearchResults\",\"parameters\":{\"query\":\"adele\"},\"header\":{\"wsKey\":\"concertboom\"}}"; 

String key = "XXXXX"; 

SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "HmacSHA1"); 
Mac mac = Mac.getInstance("HmacMD5"); 
mac.init(keySpec); 
byte[] result = mac.doFinal(data.getBytes()); 

BASE64Encoder encoder = new BASE64Encoder(); 

signature = encoder.encode(result); 

回答

2

如果我们看一下http://developers.grooveshark.com/docs/public_api/v3/,下面的代码应该工作:

private static final String EXPECTED_SIGNATURE = "cd3ccc949251e0ece014d620bbf306e7"; 

    @Test 
    public void testEnc() throws NoSuchAlgorithmException, InvalidKeyException { 
     String key = "key"; 
     String secret = "secret"; 
     String payload = "{'method': 'addUserFavoriteSong', 'parameters': {'songID': 0}, 'header': {'wsKey': 'key', 'sessionID': 'sessionID'}}"; 

     String signature = getHmacMD5(payload, secret); 
     assertEquals(EXPECTED_SIGNATURE, signature); 

    } 

    public static String getHmacMD5(String payload, String secret) { 
     String sEncodedString = null; 
     try { 
      SecretKeySpec key = new SecretKeySpec((secret).getBytes("UTF-8"), "HmacMD5"); 
      Mac mac = Mac.getInstance("HmacMD5"); 
      mac.init(key); 

      byte[] bytes = mac.doFinal(payload.getBytes("UTF-8")); 

      StringBuffer hash = new StringBuffer(); 

      for (int i=0; i<bytes.length; i++) { 
       String hex = Integer.toHexString(0xFF & bytes[i]); 
       if (hex.length() == 1) { 
        hash.append('0'); 
       } 
       hash.append(hex); 
      } 
      sEncodedString = hash.toString(); 
     } 
     catch (UnsupportedEncodingException e) {} 
     catch(InvalidKeyException e){} 
     catch (NoSuchAlgorithmException e) {} 
     return sEncodedString ; 
    } 
+0

你是最棒的,我从来没有见过此页 –