【发布时间】:2014-02-16 16:28:19
【问题描述】:
我正在尝试使用grooveshark 开始一个简单的会话,并使用sendPostReq 函数来调用startSession api。我不断收到grooveshark的以下回复。
{"errors":[{"code":2,"message":"Method not found."}]}
我们使用grooveshark api的方式是我们拥有有效载荷(在我的例子中是grooveSharkjson),我们使用密钥生成它的md5哈希并将该json发布到这个url https://api.grooveshark.com/ws3.php?sig={md5-hash-of -有效载荷}。这是正确的程序吗?
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 ;
}
我相信我生成的哈希是正确的,因为我已经使用他们在他们的网站上提供给我们的示例密钥和秘密对其进行了验证 http://developers.grooveshark.com/tuts/public_api
【问题讨论】:
标签: java api http grooveshark