2011-08-12 150 views
0

resp =(HttpWebResponse)request.GetResponse();我知道這可能是一些愚蠢的錯誤,或者只是我不熟悉Oauth的東西,但我已經停下來,我不知道該從哪裏出發,經過多次搜索和嘗試,我虛心地尋求一些幫助。401嘗試獲取請求令牌時發生錯誤

我試圖從Twitter獲取請求令牌,試圖得到一個用戶的Twitter的飼料,我不能用於其他商業原因庫...

這是迄今爲止代碼:

 Dictionary<string, string> parameters = new Dictionary<string, string>(); 
     parameters.Add("oauth_callback", "www.url.com/redirect.aspx"); 
     parameters.Add("oauth_consumer_key", <Consumer_KEY>); 
     parameters.Add("oauth_nonce", generateNonce()); 
     parameters.Add("oauth_signature_method", "HMAC-SHA1"); 
     parameters.Add("oauth_timestamp", CurrentUNIXTimestamp.Get()); 
     parameters.Add("oauth_version", "1.0"); 

     parameters = parameters.OrderBy(x => x.Key).ToDictionary(v => v.Key, v => v.Value); 
     string concat = ""; 
     string OAuthHeader = "OAuth "; 
     foreach (string k in parameters.Keys) 
     { 
      if (k == "oauth_callback") 
      { 
       concat += k + "%3D" + EncodeToUpper(parameters[k]) + "%26"; 
       OAuthHeader += k + "=" + "\"" + EncodeToUpper(parameters[k]) + "\", "; 
      } 
      else 
      { 
       concat += k + "%3D" + parameters[k] + "%26"; 
       OAuthHeader += k + "=" + "\"" + parameters[k] + "\", "; 
      } 

     } 

     concat = concat.Remove(concat.Length - 3, 3); 

     concat = "POST&" + EncodeToUpper("https://api.twitter.com/oauth/request_token") + "&" + concat; 

     //byte[] content = Encoding.UTF8.GetBytes(concat); 

     HMACSHA1 hmacsha1 = new HMACSHA1(); 
     hmacsha1.Key = Encoding.ASCII.GetBytes(string.Format("{0}&{1}", EncodeToUpper(<CONSUMER SECRET>, "")); 

     byte[] dataBuffer = System.Text.Encoding.ASCII.GetBytes(concat); 
     byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer); 

     string hash = Convert.ToBase64String(hashBytes); 
     OAuthHeader += "oauth_signature=\"" + EncodeToUpper(hash) + "\""; 

     HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.twitter.com/oauth/request_token"); 
     request.Method = "POST"; 
     request.Headers["Authorization"] = OAuthHeader; 

     StringBuilder responding = new StringBuilder(); 
     HttpWebResponse resp = null; 
     try 
     { 
      resp = (HttpWebResponse)request.GetResponse(); 
     } 
     catch (WebException exc) 
     { 
      lblError.Text = "Error Connecting to Social Network " + exc.Message; 
     } 
     if (resp != null) 
     { 
      using (StreamReader reader = new StreamReader(resp.GetResponseStream())) 
      { 
       responding.Append(reader.ReadToEnd()); 
      } 
     } 

的隨機數的一個例子是「ne8ehvVr0pW2EUxNHdxdyqbi8Fwphatt3SW1yerTyXH」並且由

  public static class CurrentUNIXTimestamp 
     { 
       public static string Get() 
       { 
        return Convert.ToString((int)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds); 
       } 
     } 

產生的CurrentUNIXTimestamp如I C我試圖儘可能多的東西想想,不再有客戶/瀏覽器問題(這是很多其他答案),服務器時間對英國夏令時是正確的(我不知道這是否是一個問題,但我試圖增加一個小時到UNIX時間戳記仍然是401),並且我已經定義了Twitter的應用程序頁面上的回調URL

我有相同的應用程序與Facebook合作(我知道它的不同的OAuth,但可以幫助)

實際錯誤出現在resp =(HttpWebResponse)request.GetResponse();它出現401錯誤。我無法從exc.response對象得到任何進一步的細節,任何人都可以說如何從VS2008中的錯誤中獲得有用的東西?

感謝您的任何答案

回答

0

我不得不執行的OAuth正在處理字符編碼的最困難的問題。這非常特別。

這是我最終爲它寫的代碼。

private static string UrlEncode(IEnumerable<KeyValuePair<string, object>> parameters) 
{ 
    StringBuilder parameterString = new StringBuilder(); 

    var paramsSorted = from p in parameters 
         orderby p.Key, p.Value 
         select p; 

    foreach (var item in paramsSorted) 
    { 
     if (parameterString.Length > 0) 
     { 
      parameterString.Append("&"); 
     } 

     if(item.Value.GetType() == typeof(string)) 
       parameterString.Append(
         string.Format(
           CultureInfo.InvariantCulture, 
           "{0}={1}", 
           UrlEncode(item.Key), 
           UrlEncode(item.Value as string))); 
    } 

    return UrlEncode(parameterString.ToString()); 
} 

public static string UrlEncode(string value) 
{ 
    if (string.IsNullOrEmpty(value)) 
    { 
     return string.Empty; 
    } 

    value = Uri.EscapeDataString(value); 

    // UrlEncode escapes with lowercase characters (e.g. %2f) but oAuth needs %2F 
    value = Regex.Replace(value, "(%[0-9a-f][0-9a-f])", c => c.Value.ToUpper()); 

    // these characters are not escaped by UrlEncode() but needed to be escaped 
    value = value 
     .Replace("(", "%28") 
     .Replace(")", "%29") 
     .Replace("$", "%24") 
     .Replace("!", "%21") 
     .Replace("*", "%2A") 
     .Replace("'", "%27"); 

    // these characters are escaped by UrlEncode() but will fail if unescaped! 
    value = value.Replace("%7E", "~"); 

    return value; 
} 

如果你真的厭倦了,你可以使用WebRequestBuilder類從我的圖書館做的所有的OAuth的東西給你:http://www.twitterizer.net/

+0

這裏是直接鏈接到我的WebRequestBuilder類:HTTP:// www.twitterizer.net/websvn/filedetails.php?repname=Twitterizer&path=%2FTwitterizer2%2FOAuth%2FWebRequestBuilder.cs ...此外,這裏是你如何實現它:http://www.twitterizer.net/websvn/filedetails .PHP?repname = Twitterizer&路徑=%2FTwitterizer2%2FOAuth%2FOAuthUtility.cs –

相關問題