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

标签 c# php json curl

我没有任何 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/

相关文章:

c# - msmq 错误 "the following errors must be resolved"

c# - 应用程序能否识别它是在云端运行还是在普通服务器上运行?

php - 如何绘制随时间推移从数据库提取的这些事件的图?

php - 将图像放入 SQLite 数据库

javascript - 使用 AJAX POST 请求发送自定义 HTTP 正文

php - 用于为 Swagger-UI 生成 JSON 文件的 Swagger-PHP

c# - 碰撞检测有问题

c# - 为 datagridview 单元格赋值

php - 通过字段名称以编程方式获取 ACF 字段键

c++ - 快速确定字符串是否为 JSON 数字的方法