I've got this piece of code that I am looping 100 times. As you can see below the number of loops is declared in the response I get from GET method. So it changes over time depending which number is inside the GET response body.
Inside the body I also have "threads": 3 So i would like to bind the number for how many threads are needed for the POST method (below)
Is it possible to do it? I've never done it before & I don't know where to begin.
for (var i = 0; i < test.loop; i++) //looping 100 times
{
Console.WriteLine("Loop count: " + i.ToString());
var newClient = new RestClient(url);
var newRequest = new RestRequest(Method.POST);
newRequest.AddHeader("Accept", "application/json");
newRequest.AddHeader("Authorization", $"{testCases.header[0].auth}");
newRequest.AddHeader("content-type", "application/json");
newRequest.AddJsonBody(bodyRequest);
var queryResult = newClient.Execute<object>(request);
var content = JsonConvert.SerializeObject(queryResult.Data);
Assert.IsTrue(content.Contains(testing.result.httpCode));
Assert.IsTrue(content.Contains(testing.result.reponseAssert.ToString()));
}
Example code for you ;
public async Task<GetResponse> GetDetails(GetRequest getRequest)
{
GetResponse apiResponseClass = new GetResponse();
var url = "your url";
var client = new RestClient(url);
var request = new RestRequest(url, Method.Post);
request.AddHeader("Password", "xxxx");
request.AddHeader("UserName", "yyyy");
request.AddHeader("Content-Type", "application/json");
var body = JsonConvert.SerializeObject(getRequest);
request.AddParameter("application/json", body, ParameterType.RequestBody);
RestResponse response = await client.ExecuteAsync(request);
var output = response.Content;
return apiResponseClass;
}
Related
I try to access to the REST API from NetExplorer. It works when I send a request with postman :
But It doesn't with my C# code :
var client = new RestClient("https://patrimoine-click.netexplorer.pro/api/auth");
var ReqAuth = new { user = "xxxxxxxxxxxxxxxxxx", password = "xxxxxxxxxxxxx" };
JsonResult result = new JsonResult(ReqAuth);
var request = new RestRequest(result.ToString(), Method.Post);
request.AddHeader("Accept", "application/json");
RestResponse response = await client.ExecuteAsync(request);
Here's the error message :
{"error":"Il n'existe aucune m\u00e9thode de l'API pouvant r\u00e9pondre \u00e0 votre appel."}
In english, there's no API method to resolve your call
If somebody can help me ...
Thanks
You are using the constructor of RestRequest wrong, the constructor does not take in the content (body) like that. Try using it with AddJsonBody like so:
var client = new RestClient("https://patrimoine-click.netexplorer.pro/api/auth");
var ReqAuth = new { user = "xxxxxxxxxxxxxxxxxx", password = "xxxxxxxxxxxxx" };
var request = new RestRequest();
request.Method = RestSharp.Method.Post;
request.AddJsonBody(ReqAuth);
request.AddHeader("Accept", "application/json");
RestResponse response = await client.ExecuteAsync(request);
Documentation: https://restsharp.dev/usage.html#request-body
I have a problem where my POST request returns back a token but when I change my code to use the token and try a GET request, it gives me a "Status:0" message. Am I writing this code wrong? I've tried adding "Bearer " + token to the Authentication.
ErrorException = {"Cannot send a content-body with this verb-type."}
Post:
var client = new RestClient("https://api.box.com/oauth2/token");
RestRequest request = new RestRequest() { Method = Method.Post };
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("client_id", $"{client_ID}");
request.AddParameter("client_secret", $"{client_secret}");
request.AddParameter("grant_type", "client_credentials");
request.AddParameter("box_subject_type", "enterprise");
request.AddParameter("box_subject_id", enterpriseID);
var response = await client.ExecuteAsync(request);
var responseMessage = JObject.Parse(response.Content);
GET:
var client2 = new RestClient("https://api.box.com/2.0/files/154072314030");
var request2 = new RestRequest() { Method = Method.Get };
request2.AddHeader("Authorization", token);
request2.AddHeader("Content-Type", "application/json");
var response2 = await client2.ExecuteAsync(request2);
var responseMessage2 = JObject.Parse(response2.Content);
Ended up using their SDK. This is how I was able to login and pull the items in the folder:
BoxFolder folderWithLink = new BoxFolder();
BoxSharedLinkRequest linkRequest = new BoxSharedLinkRequest();
int offset = 0;
int count = 0;
string folderID = "";
//create connection to Box.com
var boxConfig = new BoxConfigBuilder("CLIENT ID", "CLIENT SECRET", "Enterprise ID", "PRIVATE KEY", "PRIVATE KEY PASSWORD", "PUBLIC KEY ID").Build();
var boxJWT = new BoxJWTAuth(boxConfig);
var adminToken = await boxJWT.AdminTokenAsync();
var client = boxJWT.AdminClient(adminToken);
//Get the parent folder information and find the Batch folderID
while (folderID == "")
{
var batches = await client.FoldersManager.GetFolderItemsAsync("FOLDER ID", 250, offset);
foreach (var batchEntry in batches.Entries)
{
Console.Writeline(Batch.Name);
}
I'm working on a robotics application on Unity and I want to pass two parameters continuously from my app to a client. The code I've written causes the app to run extremely slowly (about 1 frame per 5 seconds) and it must be an issue with my async requests, but I'm not exactly sure where the problem is:
async void FixedUpdate ()
{
var client = new RestClient("http://localhost/rw/motionsystem/mechunits/ROB_1?action=mechunit-position");
client.Timeout = -1;
client.CookieContainer = login_cookie;
var request = new RestRequest(Method.POST);
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded;v=2.0");
request.AddParameter("rob_joint", manualjog);
request.AddParameter("ext_joint", "[0,0,0,0,0,0]");
var restResponse = await client.ExecuteTaskAsync(request);
}
I just solved it with a dedicated function and a while loop. The issue, as pointed out, was in FixedUpdate. Here's the working code:
public async void SyncMechanicalUnits() {
var client = new RestClient("http://localhost/rw/motionsystem/mechunits/ROB_1?action=mechunit-position");
client.Timeout = -1;
client.CookieContainer = login_cookie;
while (solveron == true)
{
var request = new RestRequest(Method.POST);
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded;v=2.0");
request.AddParameter("rob_joint", manualjog);
request.AddParameter("ext_joint", "[0,0,0,0,0,0]");
var restResponse = await client.ExecuteTaskAsync(request);
}
I've been troubleshooting this for days now but still no luck.
I'm trying to send parameters to an API link provided by Microsoft O365 Power Automate, this API requires a customer number, company code, and posting date and in return, it will send me a table with the list of items that have the same customer number, company code, and posting date. When I'm doing testing in Postman the sends status code 200, but when using VS and my code it always returns a status code 400.
SoaController.cs
[HttpPost]
public async Task<IActionResult> Index(string company, string customer, string asof)
{
using (var client = new HttpClient())
{
SoaParams soaParams = new SoaParams
{
Posting_Date = asof,
Company_Code = company,
Customer_Number = customer
};
var SoaJson = JsonConvert.SerializeObject(soaParams);
var buffer = Encoding.UTF8.GetBytes(SoaJson);
var byteContent = new ByteArrayContent(buffer);
byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
client.BaseAddress = new Uri(SD.ApiUri);
var response = await client.PostAsync(SD.ApiUri, byteContent);
if (response.IsSuccessStatusCode)
{
return RedirectToAction(nameof(Success), Json(response));
}
else
{
return RedirectToAction(nameof(Failed), Json(response));
}
}
}
The below image shows that the parameters needed are correct.
But it's SuccessStatusCode always returns false
I use a code provided by PostMan that look like this:
public List<BapiOpenItemDto> GetResponse(SoaParams soaParams, string uri)
{
var SoaJson = JsonConvert.SerializeObject(soaParams);
var client = new RestClient(uri);
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "[\r\n" + SoaJson + "\r\n]\r\n", ParameterType.RequestBody);
IRestResponse<List<BapiOpenItemDto>> response = client.Execute<List<BapiOpenItemDto>>(request);
return response.Data;
}
and its working now.
This may be too specific of an issue for assistance on, but I'm at a roadblock and don't know where else to turn.
I am POSTing to a website via REST API and their documentation states:
var client = new RestClient("https://server_name/api/import/tickets");
var request = new RestRequest(Method.POST);
request.AddHeader("authorization", "Bearer {{access_token}}");
request.AddHeader("content-type", "application/json");
request.AddHeader("accept", "application/json");
var yourArrayOfTickets = new List<Ticket>();
// TODO: populate the list
request.RequestFormat = DataFormat.Json;
request.AddBody(yourArrayOfTickets);
IRestResponse response = client.Execute(request);
I am sending
public static void MakeTicket(string token, string url,
string clientName, string clientLocation,
string ticketSource, string ticketType,
string title, string priority, string status,
string details, DateTime openDate, string queue)
{
TicketBody ticketBody = new TicketBody();
ticketBody.ClientName = clientName;
ticketBody.ClientLocation = clientLocation;
ticketBody.TicketSource = ticketSource;
ticketBody.TicketType = ticketType;
ticketBody.Title = title;
ticketBody.Priority = priority;
ticketBody.Status = status;
ticketBody.Details = details;
ticketBody.OpenDate = Convert.ToString(openDate.ToString("MM/dd/yyyy HH:mm:ss"));
ticketBody.Queue = queue;
var body = JsonConvert.SerializeObject(ticketBody);
var bodyList = new List<string>();
bodyList.Add(body);
var client = new RestClient(url + "/import/tickets");
var request = new RestRequest(Method.POST);
request.AddHeader("authorization", "Bearer " + token);
request.AddHeader("content-type", "application/json");
request.AddHeader("accept", "application/json");
request.RequestFormat = DataFormat.Json;
request.AddBody(bodyList);
IRestResponse response = client.Execute(request);
}
My bodyList JSON looks like
My response looks like
Their documentation states the required fields are:
The error message is too vague to help me, it just says I'm missing something but doesn't say what, and as far as I can tell, I'm passing in everything it needs.
As per the documentation screenshot, you have not included the required parameter AssgineeUsername. If you are specifying Queue, try passing it as empty, but include it in request.
ticketBody.Queue = queue;
ticketBody.AssgineeUsername = "";
So turns out I was building out the JSON object incorrectly for this. Instead of serializing the entire object, it needs to be a list.
Ticket ticketBody = new Ticket
{
ClientName = clientName,
ClientLocation = clientLocation,
TicketSource = ticketSource,
TicketType = ticketType,
Title = title,
Priority = priority,
Status = status,
Details = details,
OpenDate = Convert.ToString(openDate.ToString("MM/dd/yyyy HH:mm:ss")),
Queue = queue
};
List<Ticket> bodyList = new List<Ticket>();
bodyList.Add(ticketBody);