2012-05-24 55 views
1
String baseString="POST&"; 
      String subBaseString = "oauth_consumer_key="+oauth_consumer_key+"&oauth_nonce="+nonce+"&oauth_signature_method="+oauth_signature_method; 
      subBaseString += "&oauth_timestamp="+ oauth_timestamp+"&oauth_token="+oauth_token+"&oauth_version=1.0"; 
      baseString+=URLEncoder.encode(baseRequest, "UTF-8"); 
      baseString += "&" + URLEncoder.encode(subBaseString, "UTF-8"); 

      String result; 
      try { 

      SecretKeySpec signingKey = new SecretKeySpec(oauth_consumer_key.getBytes(), oauth_signature_method); 

      Mac mac = Mac.getInstance(oauth_signature_method); 
      mac.init(signingKey); 

      byte[] rawHmac = mac.doFinal(baseString.getBytes()); 

      // base64-encode the hmac 
      result = Base64.encode(rawHmac); 

      } catch (Exception e) { 
      throw new SignatureException("Failed to generate HMAC : " + e.getMessage()); 
      } 

這是我oauth_signature代碼....投遞箱oauth_signature代

,但得到的錯誤..

{ 「錯誤」:「OAuthError在API V1 +請求錯誤簽名:無效或丟失簽名「}

+0

代碼對我來說看起來很好。您是否正在使用不在簽名中的數據進行GET或POST? –

+0

使用PostMethod – behinddwalls

回答

2

如果您使用普通HTTP,則OAuth簽名,隨機數和時間戳都是必需的安全措施。但由於Dropbox API可以通過HTTPS使用,因此您可以放棄所有這些複雜性,只需使用PLAINTEXT signature mode就簡單多了。

下面是一些執行此工作的示例Java代碼。 (它將OAuth信息放入「授權」HTTP頭中,但如果需要,可以改爲URL參數。)

/** 
    * @param token 
    * For all "real" API endpoints, pass in the access token here. 
    * For "/oauth/access_token", pass in the request token here. 
    * (For "/oauth/request_token", use {@link #buildInitialOAuthHeader}.) 
    */ 
public static HttpHeader buildOAuthHeader(AppInfo appInfo, Token token) 
{ 
    StringBuilder buf = new StringBuilder(); 
    buf.append("OAuth "); 
    buf.append("oauth_token=\"").append(token.key).append("\""); 
    buf.append(", oauth_consumer_key=\"").append(appInfo.key).append("\""); 
    buf.append(", oauth_signature_method=\"PLAINTEXT\""); 
    buf.append(", oauth_signature=\"").append(appInfo.secret).append("&").append(token.secret).append("\""); 
    return new HttpHeader("Authorization", buf.toString()); 
} 

/** 
    * For "/oauth/request_token". 
    */ 
public static HttpHeader buildInitialOAuthHeader(AppInfo appInfo) 
{ 
    StringBuilder buf = new StringBuilder(); 
    buf.append("OAuth "); 
    buf.append(" oauth_consumer_key=\"").append(appInfo.key).append("\""); 
    buf.append(", oauth_signature_method=\"PLAINTEXT\""); 
    buf.append(", oauth_signature=\"").append(appInfo.secret).append("&\""); 
    return new HttpHeader("Authorization", buf.toString()); 
}