2012-11-20 110 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

你是最棒的,我從來沒有見過此頁 –