c# - C# 中的 cURL 模拟?

标签 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

请指教。由于某种原因无法弄清楚为什么代码不起作用

最佳答案

使用 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

关于c# - C# 中的 cURL 模拟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25602909/

相关文章:

c# - 计算C#中数组元素出现的频率

Linux任务调度到时分秒

java - SAS 安装因未找到 libXext 而失败

php - 使用 PHP fopen 和/或 cURL 下载外部文件

c# - C#Api Last.FM这是错误吗?

c# - 是否存在 Application.Exit() 不引发 FormClosing 事件的情况?

c# - 来自 WCF 服务的动态 XML/JSON

linux - 如何在树莓派3b+中同时使用静态以太网ip和Wi-Fi

php - 在 PHP 中获取 cURL 流

c# - 如何在 C# 中发起 HTTP 请求