首页 > 解决方案 > Java - 使用给定的 consumerKey、consumerSecret、accessToken、accessTokenSecret 和 realm 执行 oAuth1.0 认证请求

问题描述

我正在尝试将 http 帖子发送到给定的 oAuth1.0 保护端点,即提供给我的端点的所有者:

我写了一些基于如何调用 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 配置中设置,我试图找到一种方法来指定领域,但我还没有找到一种方法来做到这一点。

有人对此有任何线索吗?

标签: javaoauthhttprequest

解决方案


好吧,解决方案实际上非常简单,现在我发现它似乎很明显。将领域作为附加参数添加到 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);
}

推荐阅读