Using RestSharp 105.2.3
The API I am talking to requires use to send in a json body, but with a #c symbol as part of the field name. This is illegal in C# of course so I can't just use a dynamic object like below.
Is there a way to get the "#c" in the field name?
var client = new RestClient("https://aaa.bbb.com");
var request = new RestRequest(Method.POST);
request.AddJsonBody(new
{
#c=".Something",
username="johnsmith"
});
You could just use a string like this:
var client = new RestClient("https://aaa.bbb.com");
var request = new RestRequest(Method.POST);
string json = "{\"#c\":\".Something\", \"username\":\"johnsmith}";
request.AddJsonBody(json);
Related
How can you serialize a json object and pass it on to an api call, like the one in the example posted as an answer here Call web APIs in C# using .NET framework 3.5
System.Net.WebClient client = new System.Net.WebClient();
client.Headers.Add("content-type", "application/json");//set your header here, you can add multiple headers
string s = Encoding.ASCII.GetString(client.UploadData("http://localhost:1111/Service.svc/SignIn", "POST", Encoding.Default.GetBytes("{\"EmailId\": \"admin#admin.com\",\"Password\": \"pass#123\"}")));
In Postman I would just do this
var client = new RestClient("");
var request = new RestRequest(Method.POST);
request.JsonSerializer = new RestSharpJsonNetSerializer();
request.AddJsonBody(JsonObject);
However, as Postman is not supported in .net framework 3.5, I have to use System.Net.WebClient.
You can do what you want with WebClient (and Json.NET package) like this:
var yourObject = new YourObject {
Email = "email",
Password = "password"
};
string s = client.UploadString("http://localhost:1111/Service.svc/SignIn","POST", JsonConvert.SerializeObject(yourObject));
I have to call the following URL using RestSharp.
Some part of the uri are not standard.
How can I get to use them in
The url is the following but without the white space:
http:// mysite.com/api/v2.php?method = information :: method&token=b&target_id=0
I've tried something like this but RestSharp is not calling the URL I was expecting to call.
var client2 = new RestClient("http:// mysite.com/api/v2.php");
var request = new RestRequest("method=information::method", Method.GET);
request.AddParameter("token", authenticationToken);
request.AddParameter("target_id", targetId);
You don't mention what url your code actually calls, but I guess that your method is parsed as a file/path, and not a parameter.
var client = new RestClient("http:// mysite.com/api/");
var request = new RestRequest("v2.php", Method.GET);
request.AddParameter("method", "information::method");
request.AddParameter("token", authenticationToken);
request.AddParameter("target_id", targetId);
I am working in calling PHP API from c#. But, my problem arise when I have to pass associative array to API. I don't know exact implementation of PHP associative array in C# but I have used dictionary. It didn't works.
I have been using RestSharp to call API.
Code Implemenation:
var client = new RestClient(BaseUrl);
var request = new RestRequest(ResourceUrl, Method.POST);
IDictionary<string,string> dicRequeset = new Dictionary<string, string>
{
{"request-id", "1234"},
{"hardware-id", "CCCCXXX"},
};
request.AddParameter("request", dicRequeset);
var response = client.Execute(request);
var content = response.Content;
PHP API Implementation(Short):
* Expected input:
* string request[request-id,hardware-id]
* Return:
* code = 0 for success
* string activation_code
*/
function activate()
{
$license = $this->checkFetchLicense();
if (!$license instanceof License) return;
$response = $license->activate((array)$this->_request->getParam('request'));
}
Can someone help me to pass array to PHP API from C#?
Maybe adding the pairs makes differences in conventions in C# and PHP? Have you tried using Add?
IDictionary<string,string> dicRequeset = new Dictionary<string, string>();
dicRequeset.Add("request-id", "1234");
dicRequeset.Add("hardware-id", "CCCCXXX");
Or using indexer?
dicRequeset["request-id"] = "1234";
dicRequeset["hardware-id"] = "CCCXXX";
Or the best I can imagine is JSON as it is designed for the purpose of transmission.
var serializer = new JavaScriptSerializer();
string json = serializer.Serialize(new {request-id = "1234", hardware-id = "CCCXXX"});
The problem in the third variant despite I marked it as the best, might be that the PHP API may not decode the JSON string, because it might not be designed that way. But in general purpose JSON is meant to solve that kind of problems.
Though late post but I've solved this problem by using following approach :
var request = new RestRequest(ResourceUrl, Method.POST);
request.AddParameter("request[request-id]", hardwareId);
request.AddParameter("request[hardware-id]", hardwareId);
if I guess right, the AddParameter method of RestSharp doesn't automatically serialize an object to json thus insteadly just calls the object's toString method.
So try to get a JSON.net library and make the json encoding manually,
IDictionary<string,string> dicRequeset = new Dictionary<string, string>
{
{"request-id", "1234"},
{"hardware-id", "CCCCXXX"},
};
var jsonstr = JsonConvert.SerializeObject(dicRequeset);
request.AddParameter("request", jsonstr);
this should work.
I'm having issues making POST requests with RestSharp. My Hashtable object 'param' contains key-value pairs that must be posted to the server. I've tried several combinations and have gotten weird output on the server-side.
Example 1:
var client = new RestClient();
var request = new RestRequest(url, Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddBody (param);
Output:
Parameters: {"_json"=>[{"Key"=>"customer_subject_id", "Value"=>"300"}, {"Key"=>"client_code", "Value"=>"337"}, {"Key"=>"reservation_id", "Value"=>"9798"}, {"Key"=>"guid", "Value"=>"ODUUME4qhLmAcBVGlT4mrGbaHcbuXZID"}, {"Key"=>"customer_client_subject_id", "Value"=>"300"}, {"Key"=>"exam_code", "Value"=>"300"}, {"Key"=>"signature", "Value"=>"6bcbffb0c8ddcd89f159cf5ddd485d1eed76d1694ba329db5431f883bac3e982"}, {"Key"=>"customer_id", "Value"=>"lol"}, {"Key"=>"session_duration", "Value"=>60}]}
Example 2:
var client = new RestClient();
var request = new RestRequest(url, Method.POST);
foreach(DictionaryEntry entry in param){
request.RequestFormat = DataFormat.Json;
request.AddParameter ((entry.Key.ToString()), entry.Value);
}
Output:
Parameters: {"customer_subject_id"=>"300", "client_code"=>"337", "reservation_id"=>"9798", "guid"=>"o9LJ5e9t52xxFhxhAoHzmYd7AiQ3nu36", "customer_client_subject_id"=>"300", "exam_code"=>"300", "signature"=>"297cd7e871df885393ebe44b262cb40b8c03e55ae1f0567ff708e9811b2aedf8", "customer_id"=>"lol", "session_duration"=>"60"}
The output for #2 seems correct, but I'm getting a 401 on the server-side. Weirdly, the GET output matches that of #2, but the request is made successfully. I think the problem may be that the request, in total, is posting 10 parameters yet it should be posting one JSON formatted string in the body. Typically, I would put a JSON formatted string in the body, but even when I use a standalone JSON serializer to obtain a JSON string of the Hashtable and put in AddBody, I get the following:
Example 3:
var client = new RestClient();
var request = new RestRequest(url, Method.POST);
String paramJson = SimpleJson.SerializeObject (param);
request.RequestFormat = DataFormat.Json;
request.AddBody (paramJson);
Output:
Parameters: {"_json"=>"[{\"Key\":\"customer_subject_id\",\"Value\":\"300\"},{\"Key\":\"client_code\",\"Value\":\"337\"},{\"Key\":\"reservation_id\",\"Value\":\"9798\"},{\"Key\":\"guid\",\"Value\":\"56ZAsFtBx7jhDmdconWTb40qGirNagxK\"},{\"Key\":\"customer_client_subject_id\",\"Value\":\"300\"},{\"Key\":\"exam_code\",\"Value\":\"300\"},{\"Key\":\"signature\",\"Value\":\"57d7c878dec24da98815071d1dc3730873285b3ae65f9d98591da94266b8f7d7\"},{\"Key\":\"customer_id\",\"Value\":\"lol\"},{\"Key\":\"session_duration\",\"Value\":60}]"}
I'm mostly curious as to why the JSON string that RestSharp is creating contains "_json" at the beginning of it.
Thanks,
John
Is your server running Rails? Maybe this is relevant https://groups.google.com/forum/#!topic/rubyonrails-core/ZYBI_XHYpak
If you have control of the server side, might be better to use AddParameter and pass a JSON string, which you can parse on the server side.
var client = new RestClient("http://10.0.2.2:50670/api");
var request = new RestRequest("Inventory", Method.GET);
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
// execute the request to return a list of InventoryItem
RestResponse<JavaList<InventoryItem>> response = (RestResponse<JavaList<InventoryItem>>)client.Execute<JavaList<InventoryItem>>(request);
The content returned is a JSON string, an array of objects. The following is a short excerpt of it:
[{"Id":1,"Upc":"1234567890","Quantity":100,"Created":"2012-01-01T00:00:00","Category":"Tequila","TransactionType":"Audit","MetaData":"PATRON 750ML"},{"Id":2,"Upc":"2345678901","Quantity":110,"Created":"2012-01-01T00:00:00","Category":"Whiskey","TransactionType":"Audit","MetaData":"JACK DANIELS 750ML"},{"Id":3,"Upc":"3456789012","Quantity":150,"Created":"2012-01-01T00:00:00","Category":"Vodka","TransactionType":"Audit","MetaData":"ABSOLUT 750ml"}]
The error message:
Operation is not valid due to the current state of the object
What is wrong here? My InventoryItem has the same properties as each object in the JSON string. Am I missing a step?
I suspect that SimpleJson, used in RestSharp can't deserialise to a JavaList.
First I would try deserialising to a:
List<InventoryItem>
Failing that, I recommend ServiceStack.Text - .Net's fastest JSON library; and do:
var response = client.Execute(request);
var thingYouWant = JsonSerializer.DeserializeFromString<List<InventoryItem>>(response.Content);
This is actually what I do myself.
Edit (Thank you to commentators):
In newer versions this would now be:
var deserializer = new JsonDeserializer();
deserializer.Deserialize<List<InventoryItem>>(response);
Failing w/ auto-magic casting, I use this in a pinch:
var rc = new RestClient("https://api-ssl.bitly.com");
var rr = new RestRequest("/v3/link/clicks?access_token={access_token}&link={bitlyUrl}", Method.GET);
rr.AddUrlSegment("bitlyUrl", bitlyUrl);
rr.AddUrlSegment("access_token", BityAccessToken);
var response = rc.Execute(rr);
dynamic json = Newtonsoft.Json.Linq.JObject.Parse(response.Content);
var clicks = Convert.ToInt32(json.data.link_clicks.Value);