2014-09-01 23 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