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

时间:2011-01-17 11:39:46

标签: 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);
        }

我的猜测是我必须使用Dictionary,但在这种情况下如何将其传递给Request流? 提前谢谢。

1 个答案:

答案 0 :(得分:9)

好的,在喝一杯好咖啡之前,我应该认真地回答问题......

我的问题的答案是:

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

并将内容标题设置为:

 request.ContentType = "application/x-www-form-urlencoded";
是的,我很蠢。