Reputation: 3725
I am writing a C# client for a 3rd party API (I'm using the RestSharp nuget package). Their documentation contains PHP examples which I must translate to C#. Most of their samples are simple enough and I have been able to convert them to C# but I am struggling with one of them because it accepts an array of arrays. Here's the sample from their documentation:
$params = array (
'user_key' => 'X',
'client_id'=> 'X,
'label' => array(
array(
'language' => 'en_US',
'name' => 'English label',
),
array(
'language' => 'fr_CA',
'name' => 'French label',
),
),
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.3rdparty.com/xxx/yyy');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('apikey: YOURAPIKEY'));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
Here's what I have so far:
var labels = new Dictionary<string, string>()
{
{ "en_US", "English Label" },
{ "fr_CA", "French Label" }
};
var request = new RestRequest("/xxx/yyy", Method.POST) { RequestFormat = DataFormat.Json };
request.AddHeader("apikey", myApiKey);
request.AddParameter("user_key", myUserKey);
request.AddParameter("client_id", myClientId);
request.AddParameter("label", ???);
var client = new RestSharp.RestClient("https://api.3rdparty.com")
{
Timeout = timeout,
UserAgent = "My .NET REST Client"
};
var response = client.Execute(request);
Does anybody know how to convert the "labels" dictionary into a format that would be equivalent to PHP's http_build_query?
Upvotes: 4
Views: 1792
Reputation: 116990
http_build_query($params)
produces output that looks like this:
user_key=X&client_id=X&label%5B0%5D%5Blanguage%5D=en_US&label%5B0%5D%5Bname%5D=English+label&label%5B1%5D%5Blanguage%5D=fr_CA&label%5B1%5D%5Bname%5D=French+label
Which, decoded, looks like:
user_key=X&client_id=X&label[0][language]=en_US&label[0][name]=English label&label[1][language]=fr_CA&label[1][name]=French label
So, you should be able to do:
var request = new RestRequest("/xxx/yyy", Method.POST);
request.AddHeader("apikey", myApiKey);
request.AddParameter("user_key", myUserKey);
request.AddParameter("client_id", myClientId);
foreach (var item in labels.Select((pair, i) => new { index = i, language = pair.Key, name = pair.Value }))
{
request.AddParameter(string.Format("label[{0}][language]", item.index), item.language);
request.AddParameter(string.Format("label[{0}][name]", item.index), item.name);
}
Note that, from experimentation, I have noticed that RestSharp is encoding a space as %20
rather than as +
. Hopefully not a problem.
Upvotes: 2
Reputation: 116
You may use HttpBuildQuery that is the specular implementation of that PHP function.
Upvotes: -1