【发布时间】:2019-02-01 09:50:28
【问题描述】:
我正在尝试从https://www.reddit.com/api/v1/access_token 获取访问令牌。为此,我需要向上述 URL 发送 CLIENT_ID 和 CLIENT_SECRET。我是使用 Postman 完成的:
正如屏幕截图中突出显示的那样,我发送了一个 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);
不幸的是,两者都不起作用 - 错误仍然相同。
【问题讨论】:
-
查看我编辑的答案对我有用