发送HTTP POST负载与Java(Send HTTP Post Payload with Jav

2019-07-03 20:49发布

我试图连接到的Grooveshark 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这个要求吗?

Answer 1:

基本上,你可以使用标准的Java API做到这一点。 退房URLURLConnection ,也许HttpURLConnection 。 他们在包java.net

至于具体的API签名,尝试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();


Answer 2:

你可以看看到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();
...

干杯,



文章来源: Send HTTP Post Payload with Java