I'm trying to convert this curl command to C# using RestSharp, and I'm having problems specifically with the data parameter (token and uri variables have been replaced w/dummy values for this example):
curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' --header 'UserToken: usertoken' --header 'AppToken: apptoken' -d '[{"individualRecordNumber":"foo","score":"bar"}]' 'apiEndpoint'
I've been able to successfully do several GET requests within this same API, so I'm good with the overall request format and headers, I'm just having issues figuring out how to format the data and where to append it. Here's the rest of the request without the data:
var client = new RestClient(apiEndpoint);
var request = new RestRequest(Method.POST);
request.AddHeader("usertoken", usertoken);
request.AddHeader("apptoken", apptoken);
request.AddHeader("content-type", "application/json");
IRestResponse response = client.Execute(request);
I've tried using both AddParameter and AddJsonBody with various combinations of serialized and unserialized versions of the data.
Example of building data directly as string:
string examInfo = #"[{""individualRecordNumber"":""foo"",""score"":""bar""}]";
Example of building data as object:
object[] arrayObj = new object[1];
arrayObj[0] = new { individualRecordNumber = "foo", score = "bar" };
This is for a project with an extremely tight turnaround, so any help is much appreciated!
If you need a Post, to "wire in" the Post-Body, AddParameter has this overload
request.AddParameter("application/json", "mybody", ParameterType.RequestBody);
or , in your case
request.AddParameter("application/json", examInfo, ParameterType.RequestBody);
but maybe better (if you have later version)
request.AddJsonBody(new { A = "foo", B = "bar" });
And the initial constructor: (which you seem to have, but making sure to note it for future readers)
var request = new RestRequest(Method.POST);
More full example:
var client = new RestClient("https:blahblahblah");
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/json");
/* option1 */
request.AddParameter("application/json", "{mybody:'yes'}", ParameterType.RequestBody);
/* OR option 2 */
request.AddJsonBody(new { A = "foo", B = "bar" });
IRestResponse response = client.Execute(request);
Related
I am testing a service to which you send a json and it returns a PDF with the data you sent it. I did tests with Insomnia as shown here:
It works correctly, but trying to recover the file through code always generates an error. My code is the following:
var client = new RestClient("Api");
var request = new RestRequest(Method.GET);
request.AddHeader("content-type", "application/json");
request.AddParameter("application/json", "{\n\t\"QuotationId\": 0,\n\t\"QuotationName\": \"CasaLomas\",\n\t\"UserGUID\": \"75DB06AC-E349-4C47-A5AF-87EC63A9B8A9\",\n\t\"QuotedQuantity\": 5,\n\t\"TotalPrice\": 500,\n\t\"CopyEmail\": \"angelmg50#hotmail.com\",\n\t\"MaterialDetails\": [\n\t\t{\n\t\t\t\"SKU\": \"C05423082015140001\",\n\t\t\t\"Name\": \"PORC KONE WHITE MATE 60x30x1\",\n\t\t\t\"Quantity\": 1,\n\t\t\t\"Price\": 638.09,\n\t\t\t\"Amount\": 6380\n\t\t},\n\t\t{\n\t\t\t\"SKU\": \"C05423082015140001\",\n\t\t\t\"Name\": \"PORC KONE WHITE MATE 60x30x1\",\n\t\t\t\"Quantity\": 1,\n\t\t\t\"Price\": 638.09,\n\t\t\t\"Amount\": 6380\n\t\t},\n\t\t{\n\t\t\t\"SKU\": \"C05423082015140001\",\n\t\t\t\"Name\": \"PORC KONE WHITE MATE 60x30x1\",\n\t\t\t\"Quantity\": 1,\n\t\t\t\"Price\": 638.09,\n\t\t\t\"Amount\": 6380\n\t\t}\n\t]\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
This connects correctly with the API but apparently the json has not been sent correctly. Any idea why this happens?
I created the json with dynamic and tried to send it.
dynamic cotizacion = new JObject();
cotizacion.QuotationId = 0;
cotizacion.QuotationName = "Casa lomas 3";
cotizacion.UserGUID = "75DB06AC-E349-4C47-A5AF-87EC63A9B8A9";
cotizacion.QuotedQuantity = 6;
cotizacion.TotalPrice = 456.12;
cotizacion.CopyEmail = "angelmg50#hotmail.com";
cotizacion.MaterialDetails = new JArray(new JObject(
new JProperty("SKU", "C05423082015140001"),
new JProperty("Name", "PORC KONE WHITE MATE 60x30x1"),
new JProperty("Quantity", 1),
new JProperty("Price", 638.09),
new JProperty("Amount", 6380.30)));
var client = new RestClient("Api");
var request = new RestRequest(Method.GET);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", cotizacion, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
But this does not work either.
When I print response.Content in console it shows me the following: "Message": "Internal error when trying to generate the PDF" Value can not be null. \ R \ nParameter name: source "," StatusCode ": 3," Result ": null, "ResultList": null}
https://github.com/restsharp/RestSharp/wiki/Recommended-Usage
It seems like you are trying to add a parameter with the name "application/json". You may need to specify the name of the parameter in the endpoint and use AddObject instead of AddParameter. We can help more if you can give us some more info on your endpoint.
i'm making a console application to send email, im using the Qualtrics API REST, so i'm creating the request with RestSharp, the call that i'm using is for creating an email list, one of its parameters is the name of that list, but i want to put automatically the current date when it was created, this is the call:
static void Main(string[] args)
{
var client = new RestClient("https://qualtrics.com/API/v3/mailinglists");
var request = new RestRequest(Method.POST);
request.AddHeader("Postman-Token", "XXXX");
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("X-API-TOKEN", "XXXX");
request.AddParameter("undefined", "{\r\n \"category\": \"Test Category\",\r\n \"libraryId\": \"XXXX\",\r\n \"name\": \"Application Test\"\r\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
}
This part: "name\": \"Application Test\" is what i want to modify to put in "Application Test" the current date, Is there a way to do this?
\"date\":" + DateTime.Today.ToString()
will give you want you want.
P.S. It would be better in future not to build your JSON by hand but to serialise it from a C# object.
Below code I need to call in c#, how do we can achieve this, please help me.
import requests #requires "requests" package
import json
response = requests.post('https://scm.commerceinterface.com/api/v3/mark_exported', data={'supplier_id':'111111111', 'token':'sample-token',
'ci_lineitem_ids':json.dumps([54553919,4553920])}).json()
if response['success'] == True:
#Successfully marked as exported (only items which are not already marked exported)
pass
else:
pass
//I got sollution
C# post request
var client = new RestClient(exportUrl);
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/json");
request.AddParameter("supplier_id", apiSupplierID);
request.AddParameter("token", apiToken);
request.AddParameter("ci_lineitem_ids", exportOrders);
IRestResponse response = client.Execute(request);
in my UWP App, the user can enter a json body in a textfield and set it as body in a POST Rest-Request via restsharp portable.
So the user types this into a textbox (value is bound to requestBody):
{ "string": "Hello World"}
and then I add the string to the request:
request.AddParameter("application/json; charset=utf-8", requestBody, ParameterType.RequestBody);
The body was added, but not correct.
The Server doesn´t parse the incoming json body.
I don´t know what´s the problem, but I think some characters a not encoded correctly.
Has anyone managed it to add a json body in this way?
This solution works:
var b = JsonConvert.DeserializeObject<Object>(requestBody);
request.AddJsonBody(b);
but that´s not the clean way
Example of code that has worked for me:
var client = new RestClient("http://localhost");
var request = new RestRequest("pathtoservice", Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddParameter("application/json", "{ \"Some\": \"Data\" }", ParameterType.RequestBody);
var result = client.Execute(request);
For completeness, when using the RestSharp Portable the above would be:
var client = new RestClient("http://localhost");
var request = new RestRequest("pathtoservice", Method.POST);
var requestBody = Encoding.UTF8.GetBytes("{ \"Some\": \"Data\" }");
request.AddParameter("application/json; charset=utf-8", requestBody, ParameterType.RequestBody);
var result = client.Execute(request);
I've built my backend in rails.
My email address is "sample#zmail.com" and it's already registered. The password is "28902890" here
After giving the following command in terminal
curl -v -H 'Content-Type: application/json' -H 'Accept: application/json' -X POST https://auth-agdit.herokuapp.com/api/v1/sessions -d "{\"user\":{\"email\":\"sample#zmail\",\"password\":\"28902890\"}}"
I get this response from my backend,
{"success":true,"info":"Logged in :) ","data":{"authentication_token":"iexGFwJ6HwERQZ3wJ4NG"}}
Now I need to get this data from my Android app.
I can get json by using WebClient().downloadString() method for simple json where authentication is not needed and the request method is GET.
Now I need to get the output Json for POST method.
How can I accomplish that?
There are several methods of doing this. You could use the Xamarin component called RestSharp. This will provide you with easy methods of interfacing with your backend.
var request = new RestRequest("resource/{id}", Method.POST);
request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
request.AddUrlSegment("id", 123); // replaces matching token in request.Resource
// add parameters for all properties on an object
request.AddObject(object);
// execute the request
RestResponse response = client.Execute(request);
If you do want to simply use the WebClient class provided by the BCL you can use the WebClient.UploadString(string, string) method like so:
using (WebClient client = new WebClient())
{
string json = "{\"user\":{\"email\":\"sample#zmail\",\"password\":\"28902890\"}}";
client.UploadString("https://example.com/api/v1/sessions, json);
}
If you need more control over the request (such as setting accept headers, etc.) then you can use HttpRequest, see this question for an example of that.
This is how I did it:
WebClient wc = new WebClient();
string baseSiteString = wc.DownloadString("https://auth-agdit.herokuapp.com");
string csrfToken = Regex.Match(baseSiteString, "<meta name=\"csrf-token\" content=\"(.*?)\" />").Groups[1].Value;
string cookie = wc.ResponseHeaders[HttpResponseHeader.SetCookie];
Console.WriteLine("CSRF Token: {0}", csrfToken);
Console.WriteLine("Cookie: {0}", cookie);
wc.Headers.Add(HttpRequestHeader.Cookie, cookie);
wc.Headers.Add(HttpRequestHeader.ContentType, "application/json; charset=utf-8");
wc.Headers.Add(HttpRequestHeader.Accept, "application/json, text/javascript, */*; q=0.01");
wc.Headers.Add("X-CSRF-Token", csrfToken);
wc.Headers.Add("X-Requested-With", "XMLHttpRequest");
string dataString = #"{""user"":{""email"":""email_here"",""password"":""password_here""}}";
// string dataString = #"{""user"":{""email"":"""+uEmail+#""",""password"":"""+uPassword+#"""}}";
byte[] dataBytes = Encoding.UTF8.GetBytes(dataString);
byte[] responseBytes = wc.UploadData(new Uri("https://auth-agdit.herokuapp.com/api/v1/sessions.json"), "POST", dataBytes);
string responseString = Encoding.UTF8.GetString(responseBytes);
Console.WriteLine(responseString);
Try with this code:
Uri address = new Uri("http://example.com/insert.php");
NameValueCollection nameValueCollection = new NameValueCollection();
nameValueCollection["Name"] = "string-input";
var webClient = new WebClient();
webClient.UploadValuesAsync(address, "POST", nameValueCollection);