Java-使用给定的consumerKey,consumerSecret,accessToken,accessTokenSecret和领域执行oAuth1.0身份验证的请求

时间:2019-05-12 19:34:38

标签: java oauth httprequest

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

  • consumerKey
  • consumerSecret
  • accessToken
  • accessTokenSecret
  • 领域

我基于How to call 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:标头不是NLAuth方案。

我注意到在oAuthConsumer配置中从未真正设置过领域值,我试图找到一种指定领域的方法,但是我没有找到一种方法。

有人对此有任何线索吗?

1 个答案:

答案 0 :(得分:0)

嗯,解决方案实际上非常简单,现在我发现它似乎很明显。将域作为其他参数添加到authconsumer中对我来说很有效。

希望这对以后的人有所帮助。

public AtcUserStats getAtcUserStats(){
    return atcUserStats;
}