java - 使用 OAuth 1.0 请求 Twitter api
问题描述
我正在尝试使用 Twitter 的朋友列表 api,并且在没有任何参数的情况下成功地这样做了。
但是,每当我添加参数时,我都会收到错误“无法验证您”。cursor
而好友列表太长的时候,我只好加个参数。
当我在没有任何参数的情况下调用 api 时,我得到了朋友的用户列表,这一事实让我认为验证请求可以正常工作。
我试图将请求 url 更改为https://api.twitter.com/1.1/friends/list.json?cursor=-1这给了我身份验证错误。
我尝试同时使用https://api.twitter.com/1.1/friends/list.json和https://api.twitter.com/1.1/friends/list.json?cursor=-1来制作 oauth_signature 和它们让我失望了。
我尝试使用不同的参数,例如 screen_name 或 user_id,它们都会给我同样的错误。
我什至尝试cursor: -1
像 POST 请求一样添加标头,但这也不起作用。
现在我的代码看起来像这样
public String getFriendList() {
String baseUrl = "https://api.twitter.com/1.1/friends/list.json";
// Creates a map with all necessary headers
Map<String, String> headers = createMap();
headers.put("oauth_token", <OAuth token of user>);
String signature = createSignature("GET", baseUrl, headers, <OAuth secret of user>);
// Add oauth_signature to header
headers.put("oauth_signature", signature);
String body = sendGetRequest(baseUrl, headers);
return body;
}
public String sendGetRequest(String baseUrl, Map<String, String> parameters) throws AuthException, IOException {
try (CloseableHttpClient client = CloseableHttpClientFactory.getHttpClient()) {
HttpGet httpGet = new HttpGet(baseUrl);
if (parameters != null) {
httpGet.setHeader("Authorization", createHeader(parameters));
}
CloseableHttpResponse response = client.execute(httpGet);
if (response.getStatusLine().getStatusCode() != 200) {
LOGGER.info("GET Request Failed : " + EntityUtils.toString(response.getEntity()));
throw new Exception();
}
String responseBody = EntityUtils.toString(response.getEntity());
return responseBody;
}
}
这是工作代码。
谁能告诉我在哪里添加参数以及我在验证请求时遗漏了什么?
编辑:添加了 sendGetRequest 的代码。按照 twitter 的文档进行签名和添加标题
解决方案
推荐阅读
- excel - 基于数据透视表过滤动态更新切片器选择
- applescript - 问题:AppleScript 中的嵌套函数(处理程序)?
- javascript - jQuery突出显示表格中单个列的文本,而不是整个表格
- node.js - 检查 package.json 依赖项是否与已安装的依赖项匹配
- java - 在特定位置打印
- twilio - 如何使用 Twilio Flex SSO 令牌通过自定义 API/微服务进行身份验证
- reactjs - 表单异步验证器未呈现
- mongodb - mongodb 聚合条件 $lookup 管道性能
- python - 如何将多行合并为一行并在 Pandas 中命名?
- reactjs - 两种方式绑定和连接子类的 onChange