Send HTTP Post Payload with Java

Kooshiar Azimian picture Kooshiar Azimian · Nov 15, 2012 · Viewed 28.9k times · Source

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?

Answer

xiaofeng.li picture xiaofeng.li · Nov 15, 2012

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();