在Android中执行oAuth 1.0 API

问题描述 投票:0回答:1

您好我使用oAuth 1.0 API。每当我使用Postman执行它时它会成功响应但是当我在Android中执行它时它将返回错误身份验证失败。对于执行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;
}

在这里我知道只有参数是algo,即HmacSHA1。但是我有没有msg&key。如果我选择错误的方式来获得它,那么建议我一个正确的方法来获得它。

所以,请帮助我执行oAuth 1.0 API.Thanks

android oauth android-volley
1个回答
0
投票

从Postman复制授权标题并将其放在Volley的Authorization标题上(确保没有空格).e.g我的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;
        }

然后在凌空中使用headerData填写Authorization标头。我能够使用这个从Twitter获取json数据。如果这有帮助,请告诉我!

© www.soinside.com 2019 - 2024. All rights reserved.