我从Withings API获取用户数据访问令牌时遇到问题(api doc的第3步): http://oauth.withings.com/api/doc#api-OAuth_Authentication-access_token
服务返回"无效的签名"错误。
这是我的方法:
private static String getSignature(String url, String params, String authSecret) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
StringBuilder base = new StringBuilder();
base.append("GET&");
base.append(url);
base.append("&");
base.append(params);
byte[] keyBytes;
if (authSecret != null) {
keyBytes = (secret + "&" + authSecret + "&").getBytes(ENC);
} else {
keyBytes = (secret + "&").getBytes(ENC);
}
SecretKey key = new SecretKeySpec(keyBytes, HMAC_SHA1);
Mac mac = Mac.getInstance(HMAC_SHA1);
mac.init(key);
Base64 base64 = new Base64();
return new String(base64.encode(mac.doFinal(base.toString().getBytes(ENC))), ENC).trim();
}
public static AuthResponse getAccessToken(AuthRequest request) {
try {
CloseableHttpClient httpclient = HttpClients.createDefault();
String url = "https://oauth.withings.com/account/access_token";
URIBuilder builder = new URIBuilder(url);
List<NameValuePair> valuePairs = new ArrayList<>();
valuePairs.add(new BasicNameValuePair("oauth_consumer_key", key));
valuePairs.add(new BasicNameValuePair("oauth_nonce", "" + (int) (Math.random() * 100000000)));
valuePairs.add(new BasicNameValuePair("oauth_signature_method", "HMAC-SHA1"));
valuePairs.add(new BasicNameValuePair("oauth_timestamp", "" + (System.currentTimeMillis() / 1000)));
valuePairs.add(new BasicNameValuePair("oauth_token", request.getOauthToken()));
valuePairs.add(new BasicNameValuePair("oauth_version", "1.0"));
valuePairs.add(new BasicNameValuePair("userid", request.getUserId()));
String signature = getSignature(URLEncoder.encode(url, ENC), URLEncoder.encode(URLEncodedUtils.format(valuePairs, ENC), ENC), request.getOauthTokenSecret());
valuePairs.add(new BasicNameValuePair("oauth_signature", signature));
builder.addParameters(valuePairs);
URI uri = builder.build();
HttpGet httpget = new HttpGet(uri);
HttpResponse response = httpclient.execute(httpget);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuilder sb = new StringBuilder();
String result;
while ((result = reader.readLine()) != null) {
sb.append(result);
}
return null;
} catch (Exception e) {
throw new RuntimeException("*Error during getAccessToken request");
}
}
我也试过没有&#34; authSecret&#34;生成签名的参数(如在withings规范中),试图改变顺序和地点&#34; oauth_signature&#34;按字母顺序排列参数,但我没有成功 谁能帮我? PS:在Api文档的前两个步骤中,我使用此签名生成器成功获得了oauth_token,oauth_token_secret,userid。
答案 0 :(得分:0)
为了让STEP3正常工作,您必须删除第二个&#34;&amp;&#34;从行:
keyBytes = (secret + "&" + authSecret + "&").getBytes(ENC);
所以它变成了:
keyBytes = (secret + "&" + authSecret).getBytes(ENC);