gpt4 book ai didi

c# - C# 中的 cURL 模拟?

转载 作者:太空宇宙 更新时间:2023-11-04 11:05:05 24 4
gpt4 key购买 nike

正在尝试发送请求,但由于某种原因无法正常工作:

这应该与 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com