posting to a rest service with restsharp - c#

Ok, I'm assuming that this is an easy one, but I can't find my answer anywhere... I have a client that needs to query a rest api through .net. He sent me the url for the api, and a sample of the data. This is what he sent:
<?xml version="1.0"?>
<root>
<request>
<APIClientID>0</APIClientID >
<Version>0</Version>
<APIPassword>password</APIPassword >
<Function>functionName</Function >
<Params>
<UserId>(current-datetime)</UserId >
<page>example.aspx</page>
<application>appName</application>
<function>functionName</function>
</Params>
</request >
</root >
I'm using restsharp and I'm trying to do a post to the service. But I keep just getting back the get page with the details for the api. This is what I'm doing with restsharp...
var client = new RestClient();
client.BaseUrl = url;
var request = new RestRequest(Method.POST);
request.AddHeader("APIClientID", "4");
request.AddHeader("Version", "0");
request.AddHeader("APIPassword", "password");
request.AddHeader("Function", "TransAPIStats");
request.AddHeader("Version", "0");
request.AddParameter("Client", "test client");
request.AddParameter("UserId", DateTime.Now.ToString());
request.AddParameter("Page", "example.aspx");
request.AddParameter("Application", "app");
request.AddParameter("Function", "function");
RestResponse response = client.Execute(request);
any thoughts on where I'm going wrong would be greatly apprecaited! I'm guessing that there is something about hte xml that I'm not translating properly to the restsharp call, but I'm lost at this point... thanks!

If the POST body needs to be an XML document, use AddBody(). It defaults to serializing the object passed to it as XML. You could do this with an anonymous object that matches the schema you're trying to generate:
var client = new RestClient();
client.BaseUrl = url;
var request = new RestRequest(Method.POST);
request.AddBody(new {
root = new {
request = new {
APIClientID = 4,
Version = 0,
APIPassword = "password",
Function = "TransAPIStats",
Params = new {
UserId = "abc",
page = "example.aspx",
Application = "hrblock-cb",
Function = "ecb"
}
}
}
});
Or you could define a simple C# object that matches the schema and use that instead of the inline anonymous object.
If you need control over the serialization (the default should work based on the example data you show), you can implement your own ISerializer. Docs for that are the last section here: https://github.com/restsharp/RestSharp/wiki/Deserialization

Related

Simple PUT request to API endpoint

I'm trying to PUT JSON to the ElasticSearch api in an effort to index/insert a document in an existing index but I can't find any code examples that will actually work. I've looked at httpClient, httpWebRequests and the elastic .net plugin - NEST.
Everything works fine in something like Postman. How would the below translate to C#?
Here is an example of what I'm trying to PUT in ARC(Advanced Rest Client):
Something like this?
public void PutAPI(string basicAuth, string json)
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("authorization", $"Basic {basicAuth}");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.PutAsync("https://mydankapi.com/v1/put", new StringContent(json, Encoding.UTF8, "application/json")).Result;
if (!response.IsSuccessStatusCode)
throw new Exception(response.ReasonPhrase);
}
}
Why didn't NEST meet your requirements? According to their Getting Started - Indexing, you can index a document like this:
var tweet = new Tweet
{
Id = 1,
User = "kimchy",
PostDate = new DateTime(2009, 11, 15),
Message = "Trying out NEST, so far so good?"
};
var response = client.Index(tweet, idx => idx.Index("mytweetindex")); //or specify index via settings.DefaultIndex("mytweetindex");
All you have to do is to create a POCO class for your document type (DataMetadata?) and set the index name to data_metadata I believe.

get slack channel history in .net web api

I have fetch channel history in my .Net Web API.
The slack reference https://api.slack.com/methods/channels.history it states that we need to post the request.
Please if someone could help me with the code.
Part of Code I have implemented:
#region create json payload to send to slack
GetLatestMessage payload = new GetLatestMessage()
{
channel = "###",//value.channel_name,
token = "############################"//added the token i have generated
// user_name = value.user_name,
//text = value.text
};
#endregion
string payloadJson = JsonConvert.SerializeObject(payload);
using (WebClient client = new WebClient())
{
NameValueCollection data = new NameValueCollection();
data["payload"] = payloadJson;
var response = client.UploadValues("https://slack.com/api/channels.history", "POST", data);
//The response text is usually "ok"
string responseText = _encoding.GetString(response);
LogFileWriter("response=" + responseText);
return Request.CreateResponse(HttpStatusCode.OK);
}
I figured out the issue I was facing.I was trying to sent the post json data in to Slack url. However The Slack Web API doesn't accept JSON data.Now when I post data using standard HTTP form attributes it accepts and returns proper response.
New code:
var response = client.UploadValues("https://slack.com/api/channels.history", "POST", new NameValueCollection() {
{"token","###################"},
{"channel","######"}});
//The response text is usually "ok"
string responseText = _encoding.GetString(response);
LogFileWriter("response=" + responseText);
return Request.CreateResponse(HttpStatusCode.OK);
}

C# reading information from Android

i trying to do a simple login function.
The login will be made by an App and the information goes to a WebService (in C#).
My app is send the information to the server via HttpPost. But i can't get and return this information on the Web Service side
To make the request (android side) i was using:
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", user.getText().toString()));
params.add(new BasicNameValuePair("password", pass.getText().toString()));
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
On the WebService side, i was try to use the Serialize method, but it doens't work
Ps.: In order to test, i tried to run on another WebService (this one built with PHP), and works fine.
Any ideas how to make this work??
[Edit]
This is the web service side:
[HttpPost]
public string LogarAplicativo()
{
//Request.InputStream.Seek(0, SeekOrigin.Begin);
string jsonData = new StreamReader(Request.InputStream).ReadToEnd();
dynamic data = JObject.Parse(jsonData);
//DB validation's
var json = "";
var serializer = new JavaScriptSerializer();
json = serializer.Serialize(new { success = "0", message = "Test message!" });
return json;
}
When you send information with UrlEncodedFormEntity, it will look like a the contents of an HTTP form:
param1=value1&param2=value2
This is not JSON data, so your serialization code doesn't work because it is a completely different structure. Parsing form data requires different methods like HttpUtility.ParseQueryString.

Using Hashtable object as body/parameter for POST request (RestSharp in Xamarin Mono)

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.

Trouble with POST/PUT using RestSharp

The first listing below is using RestSharp library. The second one uses the Hammock REST API library. They are very similar. The Hammock one works, the RestSharp one does not. The 'config' object is a DTO object. The RestSharp version does not even send a message, but also does not throw an exception. Does not make a difference whether I set the Method to PUT or POST, the behavior is the same.
What on earth am I doing wrong?
##
var client = new RestClient() { BaseUrl = "http://server/AgentProxy", };
var request = new RestRequest() { Resource = "/AgentConfiguration", Method = Method.POST, RequestFormat = DataFormat.Json };
request.DateFormat = DateFormat.Iso8601;
request.AddHeader("content-type", "application/json; charset=utf-8");
request.AddBody(config);
client.Execute(request);
##
##
var client = new Hammock.RestClient() { Authority = "http://server/AgentProxy" };
var request = new Hammock.RestRequest() { Path = "/AgentConfiguration", Method = Hammock.Web.WebMethod.Post, Timeout = new TimeSpan(0, 0, 5), Credentials = null };
request.AddHeader("content-type", "application/json; charset=utf-8");
request.AddPostContent(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(config, new IsoDateTimeConverter())));
client.Request(request);
##
The two libraries seem more similar than different. Both use Newtonsoft Json library.
Thank you for your time,
Jim

Categories