2014-09-01 82 views
0

嘗試發送請求,但它並不適用於某些原因:在C#中cURL模擬?

這是應該curl命令

curl --data "client_id={client_id}&client_secret={client_secret}&code={code}&grant_type=authorization_code&redirect_uri={redirect_uri}" https://cloud.testtest.com/oauth/access_token.php 

但在C#我已經建立了工作這一個:

var webRequest = (HttpWebRequest)WebRequest.Create("https://cloud.merchantos.com/oauth/access_token.php"); 
webRequest.Method = "POST"; 

    if (requestBody != null) 
    { 
     webRequest.ContentType = "application/x-www-form-urlencoded"; 
     using (var writer = new StreamWriter(webRequest.GetRequestStream())) 
     { 
      writer.Write("client_id=1&client_secret=111&code=MY_CODE&grant_type=authorization_code&redirect_uri=app.testtest.com"); 
     } 
    } 

    HttpWebResponse response = null; 

    try 
    { 
     response = (HttpWebResponse)webRequest.GetResponse(); 
    } 
    catch (WebException exception) 
    { 
     var responseStream = exception.Response.GetResponseStream(); 
     if (responseStream != null) 
     { 
      var reader = new StreamReader(responseStream); 
      string text = reader.ReadToEnd().Trim(); 
      throw new WebException(text); 
     } 
    } 

enter image description here

請指教。由於某種原因不能確定爲什麼代碼不起作用

+3

請說明「不行」。 – Dmitry 2014-09-01 09:43:32

+0

我想我編寫的代碼不起作用,因爲我從服務器接收到400個錯誤的請求。聽起來像我在C#代碼中犯了一個錯誤 – Sergey 2014-09-01 09:46:48

+0

你需要從服務器讀取響應,它應該給你一個Json格式的錯誤描述。如果我使用你指定的細節(顯然你已經改變了證書),它會給出HTTP 400錯誤:'error_description =客戶證書無效' – DavidG 2014-09-01 09:54:53

回答

1

當使用WebRequest時,您需要遵循特定的模式,通過設置請求類型,憑證和請求內容(如果有的話)。

這通常出來到類似:

WebRequest request = WebRequest.Create("http://www.contoso.com/PostAccepter.aspx "); 
// Set the Network credentials 
request.Credentials = CredentialCache.DefaultCredentials; 
request.Method = "POST"; 
// Create POST data and convert it to a byte array. 
string postData = "This is a test that posts this string to a Web server."; 
byte[] byteArray = Encoding.UTF8.GetBytes(postData); 

request.ContentType = "application/x-www-form-urlencoded"; 

// Set the ContentLength property of the WebRequest. 
request.ContentLength = byteArray.Length; 
using (Stream dataStream = request.GetRequestStream()) 
{ 
    // Write the data to the request stream. 
    dataStream.Write(byteArray, 0, byteArray.Length); 
} 

using (WebResponse response = request.GetResponse()) 
{ 
    // Display the status. 
    Console.WriteLine(((HttpWebResponse)response).StatusDescription); 
    // Get the stream containing content returned by the server. 
    using (StreamReader reader = new StreamReader(response.GetResponseStream())) 
    { 
     Console.WriteLine(reader.ReadToEnd()); 
    } 
} 

以上是請求應該怎樣構成的樣品。查看您的示例代碼,看起來您缺少CredentialsContentLength屬性。然而,屏幕截圖顯示前者存在問題。

查看MSDN的更多詳細信息 - http://msdn.microsoft.com/en-us/library/1t38832a(v=vs.110).aspx