У меня нет никакого опыта в 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)));
Из того, что я понял, это эквивалентно установке RequestStream HttpWebRequest.Однако, какой объект я должен поместить в поток и как его сериализовать?Я использую библиотеку 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);
}
Я думаю,что я должен был бы использовать словарь, но как в таком случае передать его потоку запросов?Заранее спасибо.