2014-01-06 36 views
0

我試圖從Visual Studio訪問Salesforce數據。但是代碼返回上述異常。 我的課堂文件如下。在System.dll中發生類型'System.Net.WebException'的異常,但未在用戶代碼中處理

 public string HttpPost(string URI, string Parameters) 
     { 
      System.Net.WebRequest req = System.Net.WebRequest.Create(URI); 
      req.ContentType = "application/x-www-form-urlencoded"; 
      req.Method = "POST"; 

      // Add parameters to post 
      byte[] data = System.Text.Encoding.ASCII.GetBytes(Parameters); 
      req.ContentLength = data.Length; 
      System.IO.Stream os = req.GetRequestStream(); 
      os.Write(data, 0, data.Length); 
      os.Close(); 

      // Do the post and get the response. 
      **System.Net.WebResponse resp = req.GetResponse();** 
       if (resp == null) return null; 
       System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()); 
       return sr.ReadToEnd().Trim(); 
} 

我想調用POST方法從salesforce中檢索令牌。 '**'所包含的聲明會引發異常。

The remote server returned an error: (400) Bad Request.

任何幫助表示讚賞。

+1

捕獲異常並查看響應正文,它將獲得有關請求失敗原因的更多信息。除非您提供您正在使用的URI和params值,否則很難說更多關於它爲什麼可能不起作用的問題。 – superfell

回答

0

根本不清楚您嘗試發佈到Salesforce的數據或您使用的URL。這是一個自定義的Web服務,你試圖提交數據或類似的Web 2領先?

將Salesforce與.NET集成的一種相當標準的方法是通過Partner API or the Enterprise API。這些通常都是很好的起點,並定義了可以作爲Web引用導入到Visual Studio項目中的WSDL。還有REST apis。既然你要留言

"login.salesforce.com/services/oauth2/token"

我是你的使用Web Server OAuth 2 Authentication Flow和假設你有你現在使用請求訪問令牌的授權碼。

您發佈到該URL的參數應該是這個樣子(注意,這是直接從Salesforce的數據採取所以它不應該包含任何敏感信息):

grant_type=authorization_code&code=aPrxsmIEeqM9PiQroGEWx1UiMQd95_5JUZ VEhsOFhS8EVvbfYBBJli2W5fn3zbo.8hojaNW_1g%3D%3D&client_id=3MVG9lKcPoNI NVBIPJjdw1J9LLM82HnFVVX19KY1uA5mu0QqEWhqKpoW3svG3XHrXDiCQjK1mdgAvhCs cA9GE&client_secret=1955279925675241571& redirect_uri=https%3A%2F%2Fwww.mysite.com%2Fcode_callback.jsp

你將要使用Salesforce在上一步中返回給您的授權碼以及您自己的client_id和client_secret。你也可以根據你的需要設置redirect_uri。


要建立一個用戶名和密碼的REST接口:Understanding the Username-Password OAuth Authentication Flow

您將要設置的grant_type密碼,並提供用戶名和密碼。這應該被張貼到https://login.salesforce.com/services/oauth2/token

grant_type=password&client_id=3MVG9lKcPoNINVBIPJjdw1J9LLM82Hn FVVX19KY1uA5mu0QqEWhqKpoW3svG3XHrXDiCQjK1mdgAvhCscA9GE&client_secret= 1955279925675241571&username=testuser%40salesforce.com&password=mypassword123456

然後,您可以從響應得到access_token

+0

我正在使用rest api。使用的網址如下,string URI =「https://login.salesforce.com/services/oauth2/token」; – user3065219

+0

看起來您是[Salesforce.com REST API](http://danlb.blogspot.co.nz/2010/10/salesforcecom-rest-api.html)中的示例,是否正確? –

+0

是的,這是正確的。但我沒有授權碼。你可以給一個偉大的類型作爲密碼的例子嗎? – user3065219

相關問題