java - Java - 使用给定的 consumerKey、consumerSecret、accessToken、accessTokenSecret 和 realm 执行 oAuth1.0 认证请求
问题描述
我正在尝试将 http 帖子发送到给定的 oAuth1.0 保护端点,即提供给我的端点的所有者:
- 消费者密钥
- 消费者秘密
- 访问令牌
- accessTokenSecret
- 领域
我写了一些基于如何调用 API (Oauth 1.0) 的代码?
public class HttpAuthPost {
public HttpAuthPost() {
realmID = "XXXXXXX";
String consumerKey = "kjahsdkjhaskdjhaskjdhkajshdkajsd";
String consumerSecret = "jklahsdkjhaskjdhakjsd";
String accessToken = "iuyhiuqhwednqkljnd";
String accessTokenSecret = "oihkhnasdiguqwd56qwd";
setupContext(consumerKey, consumerSecret, accessToken, accessTokenSecret);
}
public void setupContext(String consumerKey, String consumerSecret, String accessToken, String accessTokenSecret) {
this.oAuthConsumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
oAuthConsumer.setTokenWithSecret(accessToken, accessTokenSecret);
oAuthConsumer.setSigningStrategy(new AuthorizationHeaderSigningStrategy());
}
public void authorize(HttpRequestBase httpRequest) throws FMSException {
try {
oAuthConsumer.sign(httpRequest);
} catch (OAuthMessageSignerException e) {
throw new FMSException(e);
} catch (OAuthExpectationFailedException e) {
throw new FMSException(e);
} catch (OAuthCommunicationException e) {
throw new FMSException(e);
}
}
public String executeGetRequest(String customURIString, String _content) throws UnsupportedEncodingException {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost httpRequest = null;
//Preparing HttpEntity and populating httpRequest
try {
authorize(httpRequest);
} catch (FMSException e) {
e.printStackTrace();
}
HttpResponse httpResponse = null;
try {
HttpHost target = new HttpHost(uri.getHost(), -1, uri.getScheme());
httpResponse = client.execute(target, httpRequest);
// Process response and generate output
return output;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
我做了一些测试,我收到了这个错误: USER_ERROR : header is not NLAuth scheme。
我注意到领域值实际上从未在 oAuthConsumer 配置中设置,我试图找到一种方法来指定领域,但我还没有找到一种方法来做到这一点。
有人对此有任何线索吗?
解决方案
好吧,解决方案实际上非常简单,现在我发现它似乎很明显。将领域作为附加参数添加到 authconsumer 对我有用。
希望这对将来的其他人有所帮助。
public void setupContext(String consumerKey, String consumerSecret, String accessToken, String accessTokenSecret) {
this.oAuthConsumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
oAuthConsumer.setTokenWithSecret(accessToken, accessTokenSecret);
oAuthConsumer.setSigningStrategy(new AuthorizationHeaderSigningStrategy());
HttpParameters parameters = new HttpParameters();
parameters.put("realm", realmID);
oAuthConsumer.setAdditionalParameters(parameters);
}
推荐阅读
- google-cloud-platform - 如何使用 Google Video Intelligence API 跟踪眼球运动?
- python - 我想通过 PyCall 在 Julia 上使用 OpenCV
- visual-studio-2019 - Blazor 应用程序中的结构,为什么我不能拥有一个?
- twig - 在 template_from_string 函数中使用树枝过滤器
- java - 如何在 Windows 上使用 JDK 15 安装 Jenkins
- java - 可以将 @Component 对象初始化为数据类中的私有最终属性吗?
- javascript - 当数量增加导致价格上涨时
- matlab - 如何获得矩阵的所有可能的置换矩阵
- html - 更改 Bootstrap 导航栏链接的颜色
- python - 如何使用 Flask、Python 在 SQLite 数据库中添加图像文件