c#中的cURL模拟?

时间:2014-09-01 09:38:25

标签: c# linux 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

请指教。出于某种原因无法弄清楚代码无法正常工作的原因

1 个答案:

答案 0 :(得分: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