我正在尝试从https://www.reddit.com/api/v1/access_token获取访问令牌。为此,我需要向上述URL发送一个CLIENT_ID
和一个CLIENT_SECRET
。我是使用邮递员这样做的:
如屏幕快照中突出显示的那样,我已经发送了一个grant_type
作为一个GET
参数,值是client_credentials
和一个Authorization
参数,值是Basic heregoestheencodedkeyandid
。请求类型设置为POST
。它正常工作-我在JSON
响应中得到了一个访问令牌。
但是,当我尝试通过Java来做同样的事情时,我收到了Server returned HTTP response code: 411
错误:
public class RedditExample {
private static String loginLink = "https://www.reddit.com/api/v1/access_token";
public static void main(String[] args) {
RedditExample redditExample = new RedditExample ();
redditExample.login();
}
public boolean login() {
try {
URL loginURL = new URL(loginLink + "?grant_type=client_credentials");
HttpURLConnection connection = (HttpURLConnection) loginURL.openConnection();
setupPOSTConnection(connection);
InputStream input = connection.getInputStream();
String inputString = new Scanner(input, "UTF-8").useDelimiter("\\Z").next();
System.out.println(inputString);
}
catch (Exception e) {
System.out.println(e.toString());
}
return true;
}
private static void setupPOSTConnection(HttpURLConnection connection) throws Exception {
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Authorization", "Basic heregoestheencodedkeyandid");
connection.connect();
}
}
与Postman相比,我不确定我在这里所做的不同,所以我们将不胜感激。
编辑:这是我尝试添加的内容:
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Length", "0");
connection.setRequestProperty("Content-Length", "10");
String userAgent = "test /u/someuser";
connection.setRequestProperty("User-Agent", userAgent);
不幸的是,这两个都不起作用-错误仍然相同。
答案 0 :(得分:3)
HttpUrlConnection不采用显式设置content-length的方法。因此,只需提供没有内容的请求正文即可。
StringBuilder postDataBuilder = new StringBuilder();
byte[] postData = postDataBuilder.toString().getBytes("UTF-8");
OutputStream out = conn.getOutputStream();
out.write(postData);
out.close();
所以方法将是这样的:-
private static void setupPOSTConnection(HttpURLConnection connection) throws Exception {
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Authorization", "Basic heregoestheencodedkeyandid");
StringBuilder postDataBuilder = new StringBuilder();
byte[] postData = postDataBuilder.toString().getBytes("UTF-8");
OutputStream out = conn.getOutputStream();
out.write(postData);
out.close();
connection.connect();
}
我还发现了另一种简单添加一行的方法:-
private static void setupPOSTConnection(HttpURLConnection connection) throws Exception {
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Authorization", "Basic heregoestheencodedkeyandid");
conn.setFixedLengthStreamingMode(0);
connection.connect();
}
答案 1 :(得分:0)
HTTP状态代码411(必需的长度)由服务器发送作为响应。 如果没有Content-Length标头,则服务器可能会接受或可能不会接受内容,并且此API似乎很挑剔。请参阅this post,详细介绍使用Java进行有效的POST连接。