使用Java发送HTTP Post Payload

时间:2012-11-15 11:01:29

标签: java httprequest payload grooveshark

我正在尝试连接到groovehark API,这是http请求

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

我的问题是如何通过Java发送此请求?

2 个答案:

答案 0 :(得分:4)

基本上,您可以使用标准Java API来完成。查看URLURLConnectionHttpURLConnection。它们在java.net包中。

关于API特定签名,请尝试here.

中的sStringToHMACMD5

请记住更改您的API密钥,这非常重要,因为每个人都知道它。

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

答案 1 :(得分:0)

您可以查看Commons HttpClient包。

创建POST非常简单,特别是您可以复制此处的代码: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();
...

干杯,