2011-01-05 687 views
2

此代碼適用於Outlook插件。我們試圖張貼到網頁,並收到此錯誤:出現此錯誤:「遠程服務器返回錯誤:(422)無法處理的實體。」當從C#發佈到RoR時

The remote server returned an error: (422) Unprocessable Entity. 

的C#代碼是在這裏:

webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); 
     ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding(); 
     Byte[] postData = asciiEncoding.GetBytes("[email protected]&password=hunter2"); 
     char[] resultHTML = asciiEncoding.GetChars(webClient.UploadData("http://url", "POST", postData)); 
     string convertedResultHTML = new string(resultHTML); 

任何想法可能是什麼造成的?

回答

0

將下面的代碼添加到代碼上方。

您是否試圖訪問需要身份驗證的頁面?

+0

我補充說,但我仍然得到同樣的錯誤返回XML而不是隻非結構化文本解決。我正在訪問軌道控制器上的紅寶石,它什麼也不做,只能通過Outlook插件發佈並呈現一些文本。根本沒有任何邏輯。 – tipu 2011-01-24 12:06:15

1

由於功能有限,我避免使用WebClient並使用WebRequest代替。下面的代碼:

  1. 沒有想到會返回一個HTTP 100個狀態碼,
  2. 創建CookieContainer儲存我們拿起任何餅乾,
  3. 設置內容長度頭和
  4. UrlEncode是發佈數據中的每個值。

請嘗試以下操作,看看它是否適用於您。

System.Net.ServicePointManager.Expect100Continue = false; 
System.Net.CookieContainer cookies = new System.Net.CookieContainer(); 

// this first request just ensures we have a session cookie, if one exists 
System.Net.WebRequest req = System.Net.WebRequest.Create("http://localhost/test.aspx"); 
((System.Net.HttpWebRequest)req).CookieContainer = cookies; 
req.GetResponse().Close(); 

// this request submits the data to the server 
req = System.Net.WebRequest.Create("http://localhost/test.aspx"); 
req.ContentType = "application/x-www-form-urlencoded"; 
req.Method = "POST"; 
((System.Net.HttpWebRequest)req).CookieContainer = cookies; 

string parms = string.Format("email={0}&password={1}", 
    System.Web.HttpUtility.UrlEncode("[email protected]"), 
    System.Web.HttpUtility.UrlEncode("hunter2")); 
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(parms); 
req.ContentLength = bytes.Length; 

// perform the POST 
using (System.IO.Stream os = req.GetRequestStream()) 
{ 
    os.Write(bytes, 0, bytes.Length); 
} 

// read the response 
string response; 
using (System.Net.WebResponse resp = req.GetResponse()) 
{ 
    if (resp == null) return; 
    using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream())) 
    { 
     response = sr.ReadToEnd().Trim(); 
    } 
} 
// the variable response holds the results of the request... 

學分:HanselmanSimon(SO問題)

1

這是RoR應用程序告訴你,你還沒有形成一個請求,它可以處理;目標腳本存在(否則你會看到一個404),請求正在被處理(否則你會得到一個400錯誤)並且它已被正確編碼(或者你會得到一個415錯誤),但實際的指令可以'不能進行。

看着它,你似乎正在加載一些電子郵件信息。 RoR應用程序可能會告訴您用戶名和密碼錯誤,或用戶不存在或其他內容。這取決於RoR應用程序本身。

我覺得代碼本身很好,這只是在另一端的應用程序不滿意你做的問題。在請求信息中是否缺少其他內容,如命令? (例如command=getnetemails&[email protected]&password=hunter2)您確定您傳遞的電子郵件/密碼組合良好嗎?

有關422錯誤的更多信息,請參閱here

1

如果您發送的字符不在ASCII範圍內,則POST數據必須在作爲ASCII發送出去之前進行編碼。你應該嘗試類似:

Byte[] postData = asciiEncoding.GetBytes(HttpUtility.UrlEncode("[email protected]&password=hunter2")); 
+0

您應該分別編碼每個參數的值 – 2014-07-29 22:03:09

0

它是由在回報率方面

+0

通過更改響應的結構如何解決處理請求的錯誤?我曾預計你的應用會返回500錯誤。 – arcain 2011-01-31 13:49:33

相關問題