Send HTTP Post Payload with Java

一曲冷凌霜 提交于 2019-12-01 18:04:15

问题


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?


回答1:


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



回答2:


You could look into the Commons HttpClient package.

It is fairly straight forward to create POST's, specifically you could copy the code found here: http://hc.apache.org/httpclient-3.x/methods/post.html:

PostMethod post = new PostMethod( "http://api.grooveshark.com/ws3.php?sig=f699614eba23b4b528cb830305a9fc77" );
NameValuePair[] data = {
    new NameValuePair( "method", "addUserFavoriteSong..." ),
    ...
};
post.setRequestBody(data);
InputStream in = post.getResponseBodyAsStream();
...

Cheers,



来源:https://stackoverflow.com/questions/13396171/send-http-post-payload-with-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!