我试图使用grooveshark启动一个简单的会话,并使用sendPostReq函数调用startSession api。我一直从grooveshark那里得到以下回复。
{"errors":[{"code":2,"message":"Method not found."}]}我们使用grooveshark的方式是我们有有效负载(在我的例子中是grooveSharkjson),我们使用秘密密钥生成md5哈希,并将该json发布到这个url https://api.grooveshark.com/ws3.php?sig={md5-散列的有效载荷}。这是正确的程序吗?
下面还显示了sendPostReq函数和生成md5哈希的代码
public static void sendPostReq() throws Exception{
String grooveSharkjson = "{'method':'startSession','header':{'wsKey':'wskey'}}";
String key = "secret"; // Your api key.
String sig = SecurityHelper.getHmacMD5(grooveSharkjson, key);
URL url = new URL("https://api.grooveshark.com/ws3.php?sig=" + sig);
URLConnection connection = url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
OutputStream os = connection.getOutputStream();
PrintWriter pw = new PrintWriter(new OutputStreamWriter(os));
pw.write(grooveSharkjson);
pw.close();
InputStream is = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = null;
StringBuffer sb = new StringBuffer();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
String response = sb.toString();
System.out.println(response);
}
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 ;
}我相信我正在生成的散列是正确的,因为我已经用他们在他们的网站api上提供的示例密钥和秘密来验证它。
发布于 2014-01-25 17:43:11
我知道我在20分钟前就发了这个问题,但我刚刚找到了解决办法。json字符串有一个问题,特别是我生成它的方式。这就是它的生成方式。
String grooveSharkjson = "{\"method\":\"startSession\",\"header\":{\"wsKey\":\"wsKey\"},\"parameters\":[]}";我没想到解决方案会如此明显,但这是从这里我得到了一个如何解决我的问题的想法-我测试了我的密钥和秘密在他们的沙箱(api/v3/sandbox.php),并双重检查md5的签名。
https://stackoverflow.com/questions/21353665
复制相似问题