Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send HTTP Post Payload with Java

I'm trying to connect to the grooveshark API, this is the http request

POST URL
http://api.grooveshark.com/ws3.php?sig=f699614eba23b4b528cb830305a9fc77
POST payload
{"method":'addUserFavoriteSong",'parameters":{"songID":30547543},"header": 
{"wsKey":'key","sessionID":'df8fec35811a6b240808563d9f72fa2'}}

My question is how can I send this request via Java?

like image 658
Kooshiar Azimian Avatar asked Oct 05 '22 23:10

Kooshiar Azimian


1 Answers

Basically, you can do it with the standard Java API. Check out URL, URLConnection, and maybe HttpURLConnection. They are in package java.net.

As to the API specific signature, try sStringToHMACMD5 found in here.

And remember to CHANGE YOUR API KEY, this is very IMPORTANT, since everyone knows it know.

String payload = "{\"method\": \"addUserFavoriteSong\", ....}";
String key = ""; // Your api key.
String sig = sStringToHMACMD5(payload, key);

URL url = new URL("http://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(payload);
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();
like image 139
xiaofeng.li Avatar answered Oct 10 '22 04:10

xiaofeng.li