drkxgs9358
drkxgs9358
2017-03-18 22:12

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

已采纳

I have written this code in PHP to make a HTTP request to my server to retrieve my data:

<?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); 

?> 

And this works good. Data is returned in JSON format. Now I'm trying to do exactly the same thing but in .NET

I have managed to recreate in .NET C# exactly the same postData parameter as in PHP, but I'm not sure how to pass it in C# with the request itself... So I've decided to use .NET's restsharp library to make the request like this:

  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);

        }

Please note in C# and in PHP variables:

$post_data 

and 

var postdata

are exactly identical. Now I just don't know how to pass them alongside the request because the server always responds me that request data was empty..

What am I doing wrong here?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • doushajian2018 doushajian2018 4年前

    try
    request.AddBody(YOUR_JSON_STUFF);
    and request.RequestFormat = DataFormat.Json;

    before client.execute()

    点赞 评论 复制链接分享