【问题标题】:Execute oAuth 1.0 API in Android在 Android 中执行 oAuth 1.0 API
【发布时间】:2019-03-16 00:40:30
【问题描述】:

您好,我使用的是 oAuth 1.0 API。每当我用 Postman 执行它时,它都会成功响应,但是当我在 Android 中执行它时,它会返回错误 Authentication fail。 对于执行 API,我使用了凌空。 我有信息

  • 消费者密钥
  • 消费者秘密
  • 签名方法 (HMAC-SHA1)
  • 时间戳
  • 随机数
  • 版本 (1.0)

我已经在邮递员的授权部分传递了这个信息,它返回了成功的结果。现在我需要将此信息传递给 Volley Request 但它每次都返回身份验证失败错误。 对于身份验证,我使用 oAuth 详细信息创建字符串并将其传递给标题。

Map<String, String> headers = new HashMap<String, String>();
        Long tsLong = System.currentTimeMillis() / 1000;
        final String ts = tsLong.toString();

        String value = "OAuth " + "oauth_consumer_key" + "=\"OAUTH_CONSUMER_KEY\","
                + "oauth_signature_method" + "=\"" + "HMAC-SHA1" + "\","
                + "oauth_timestamp" + "=\"" + ts + "\","
                + "oauth_nonce" + "=\"" + UUID.randomUUID().toString() + "\","
                + "oauth_version" + "=\"" + "1.0" + "\","
                + "oauth_signature" + "=\"" + OAUTH_SIGNATURE + "\"";
        headers.put("Authorization", value);

OAUTH_SIGNATURE 由 Postman 自动生成。但在 android 中我不知道如何生成它。 谷歌搜索后,我得到了生成 oAuth 签名的方法。

public static String hmacDigest(String msg, String keyString, String algo) {
    String digest = null;
    try {
        SecretKeySpec key = new SecretKeySpec((keyString).getBytes("UTF-8"), algo);
        Mac mac = Mac.getInstance(algo);
        mac.init(key);
        byte[] bytes = mac.doFinal(msg.getBytes("ASCII"));
        StringBuffer hash = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                hash.append('0');
            }
            hash.append(hex);
        }
        digest = hash.toString();
    } catch (UnsupportedEncodingException e) {
    } catch (InvalidKeyException e) {
    } catch (NoSuchAlgorithmException e) {
    }
    return digest;
}

这里我知道唯一的参数是算法 HmacSHA1。但是有我没有的味精和密钥。 如果我选择了错误的获取方式,请建议我正确的获取方式。

所以,请帮助我执行 oAuth 1.0 API。谢谢

【问题讨论】:

    标签: android oauth android-volley


    【解决方案1】:

    从 Postman 复制授权标头并将其放在 Volley 的授权标头上(确保您没有空间)。例如我的 Config.java 包含:

    public static final String headerData = "your_auth_data_from_postman";
    public static final String TWITTER_SEARCH_URL = "url_for_get_or_post";
    

    然后在凌空做这个

     @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                params.put("Content-Type", "application/x-www-form-urlencoded");
                params.put("Authorization", Config.headerData);
                return params;
            }
    

    然后在 volley 上用 headerData 填写 Authorization 标头。我能够使用它从 Twitter 获取 json 数据。让我知道这是否有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-14
      • 2018-04-12
      • 1970-01-01
      • 2014-12-24
      • 1970-01-01
      • 2015-11-26
      相关资源
      最近更新 更多