将PHP http请求转换为C#.NET

时间:2017-03-18 22:12:13

标签: c# php asp.net asp.net-mvc curl

我已用PHP编写此代码,向我的服务器发出HTTP请求以检索我的数据:

res+=instanceNums[index];

这很好用。数据以JSON格式返回。现在我试图在.NET中完成同样的事情

我已经设法在.NET C#中重新创建与PHP中完全相同的postData参数,但是我不确定如何在C#中传递请求本身...所以我已经决定使用.NET的restsharp库来发出如下命令:

<?php


$client_secret= '';
$data= array(

'email' => '**********',

'password' => '******',

'client_id' => '*******'
);

$api_url='******';

$json_data=json_encode($data);

$signature_string = md5($json_data . $client_secret); 


$post_data = 'signature='.$signature_string.'&data='.urlencode($json_data);

$curl = curl_init($api_url); 
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1);

curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); 

curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($curl, CURLOPT_POST, 1); 

curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);

$result = curl_exec($curl); 

print_r($result);


curl_close($curl); 

?> 

请注意在C#和PHP变量中:

  public void GetResponse()
        {
            string client_secret = "*****";

            var serializer = new JavaScriptSerializer();
            string json_data = serializer.Serialize(new { email = "*****", password = "*****", client_id = "*****" });

            var signature_string = CalculateMD5Hash(json_data + client_secret).ToLower();

            var postData = "signature=" + signature_string + "&data=" + Server.UrlEncode(json_data);
            var client = new RestClient("mysite.com");
            var request = new RestRequest(Method.POST);
            request.AddHeader("content-type", "application/x-www-form-urlencoded");
            request.AddHeader("cache-control", "no-cache");
            request.AddParameter("application/x-www-form-urlencoded", "signature="+signature_string, ParameterType.RequestBody);
            request.AddParameter("application/x-www-form-urlencoded", "data=" +json_data, ParameterType.RequestBody);

            IRestResponse response = client.Execute(request);

        }

完全相同。现在我只是不知道如何将它们与请求一起传递,因为服务器总是回应我请求数据是空的..

我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

试试 request.AddBody(YOUR_JSON_STUFF);
request.RequestFormat = DataFormat.Json;

之前client.execute()