使用oAuth - fatsecret API

时间:2016-10-23 11:39:12

标签: java android rest api oauth

我尝试向使用oAuth的REST API发送有效请求。我一直收到回复:“签名无效”

以下是我生成请求的步骤:

构建请求:

public String buildRequest() {

    ArrayList<String> params = new ArrayList<>(generateParams());
    params.add("oauth_signature=" + sign(buildSignatureBaseString()));

    Collections.sort(params);

    return join(params.toArray(template), "&");
}

创建签名基本字符串:

public String buildSignatureBaseString(){

    StringBuilder builder = new StringBuilder();

    builder.append(METHOD);
    builder.append("&");
    builder.append(percentEncoding(URL));
    builder.append("&");
    builder.append(percentEncoding(join(generateParams().toArray(template), "&")));

    return builder.toString();
}

生成按自然顺序排序的参数:

private ArrayList<String> generateParams() {

    ArrayList<String> params = new ArrayList<>();

    params.add("oauth_consumer_key=" + "...");
    params.add("oauth_signature_method=HMAC-SHA1");
    params.add("oauth_timestamp=" + Long.valueOf(System.currentTimeMillis() / 1000).toString());
    params.add("oauth_nonce=" + getNonce());
    params.add("oauth_version=1.0");
    params.add("format=json");
    params.add("method=foods.search");
    params.add("search_expression=pasta");

    Collections.sort(params);

    return params;
}

创建签名基本字符串:

public String buildSignatureBaseString(){

    StringBuilder builder = new StringBuilder();

    builder.append(METHOD);
    builder.append("&");
    builder.append(percentEncoding(URL));
    builder.append("&");
    builder.append(percentEncoding(join(generateParams().toArray(template), "&")));

    return builder.toString();
}

使用HMAC-SHA1生成签名:

public String sign(String sbs) {

    String key = <SharedSecret> + "&";
    SecretKeySpec sk = new SecretKeySpec(key.getBytes(Charset.forName("UTF-8")), ALGORITHM);
    try {
        Mac m = Mac.getInstance(ALGORITHM);
        m.init(sk);
        byte[] hmacEncoded = m.doFinal(sbs.getBytes(Charset.forName("UTF-8")));
        byte[] base64Encoded = Base64.encode(hmacEncoded, Base64.DEFAULT);
        return Uri.encode(new String(base64Encoded, Charset.forName("UTF-8")));
    } catch (java.security.NoSuchAlgorithmException e) {
        Log.w("FatSecret_TEST FAIL", e.getMessage());
        return null;
    } catch (java.security.InvalidKeyException e) {
        Log.w("FatSecret_TEST FAIL", e.getMessage());
        return null;
    }
}

有更多有经验的人可以帮忙吗?

此致

1 个答案:

答案 0 :(得分:0)

来自generateParams all的参数条目的格式为tag = value。您的sign方法似乎只返回一个值。

并且:你确定签名方法没有抛出?在这种情况下,你会返回null,你应该检查调用方法,如果它不为null,只将它添加到params