gpt4 book ai didi

c# - 如何将 PHP cURLcode 转换为 C# HttpWebRequest?

转载 作者:行者123 更新时间:2023-11-30 19:32:52 27 4
gpt4 key购买 nike

我没有任何 php 方面的经验,但我需要创建与此代码等效的 C#:

<?
$theData = array(
'action'=>'login',
'data'=>array(
'username'=>'(the username to be used)',
'password'=>'(the password)'
),
);
echo "REQUEST:\n";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, '(the service url)');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('query'=>json_encode($theData)));
curl_setopt($ch, CURLOTP_SSL_VERIFYPEER, false);
$login = curl_exec($ch);
#echo $login;
var_dump(json_decode($login, true));
#cho "\n";
curl_close($ch);

在 C# 中。

现在,我无法绕过的一件事是这一行:

curl_setopt($ch, CURLOPT_POSTFIELDS , array('query'=>json_encode($passedData))); 

据我所知,这相当于设置 HttpWebRequest 的 RequestStream。但是,我应该在流中放入什么样的对象,我应该如何序列化它呢?我正在使用此处的 Json.NET 库:http://json.codeplex.com/我当前的 C# 代码是这样的(这是测试代码,只是为了看看它是如何工作的):

        StringWriter sw = new StringWriter(new StringBuilder());
using (JsonWriter jwr = new JsonTextWriter(sw))
{
jwr.Formatting = Formatting.Indented;
jwr.WriteStartObject();
jwr.WritePropertyName("action");
jwr.WriteValue("login");
jwr.WritePropertyName("data");
jwr.WriteStartObject();
jwr.WritePropertyName("username");
jwr.WriteValue((the username));
jwr.WritePropertyName("password");
jwr.WriteValue((the password));
jwr.WriteEnd();
jwr.WriteEndObject();
}
string data = sw.ToString();
Console.WriteLine(data); //yes, the json string is correct
//uri of the service
Uri address = new Uri((the service uri));
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
ServicePointManager.ServerCertificateValidationCallback = delegate
{
return
true; //always trust the presented cerificate
};
request.Method = "post";
request.ContentType = "application/json";
string response = null;
try
{
using (Stream s = request.GetRequestStream())
{
using (StreamWriter stw = new StreamWriter(s))
{
stw.Write(data); //obviously this adds just the json object
//and not the array() map, hence the server
//returns an error.
}
}

using (HttpWebResponse resp = request.GetResponse() as HttpWebResponse)
{
Console.WriteLine();
var reader = new StreamReader(resp.GetResponseStream(), Encoding.UTF8);
response = reader.ReadToEnd();
}
Console.WriteLine(response);
}

我的猜测是我必须使用字典,但在那种情况下我如何将它传递给请求流?提前谢谢你。

最佳答案

好吧,我真的应该在喝一杯好咖啡之前不问问题......

我的问题的答案是这样的:

stw.Write("query="+data);

并将内容 header 设置为此:

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

是的,我很笨。

关于c# - 如何将 PHP cURLcode 转换为 C# HttpWebRequest?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4712706/

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