How to fix 400 Response Incoming from Microsoft Azure Computer Vision service - c#

I subscribed to Computer Vision API on RapidAPI. When I'm testing the API on the RapidAPI platform, it's working perfectly. But when I'm calling it from my app, it responding 400 Bad request.
How can I fix this problem?
I'm using the RESTSharp library.
Here's my code -
public static IRestResponse GetClassifiedImageData()
{
var client = new RestClient("{Client Path}");
var request = new RestRequest(Method.POST);
request.AddHeader("x-rapidapi-host", "{Rapid API host}");
request.AddHeader("x-rapidapi-key", "{My API key}");
request.AddHeader("content-type", "application/json");
request.AddHeader("accept", "application/json");
request.AddParameter("application/json", "{\"url\":\"Image URL\"}", ParameterType.RequestBody);
return client.Execute(request);
}
And if I call asyncronusly, I get this message -
System.Runtime.CompilerServices.AsyncTaskMethodBuilder1+AsyncStateMachineBox1[System.String,ComputerVision.Program+d__2]
Async Code-
public static async Task<IRestResponse> GetClassifiedImageData2()
{
var client = new RestClient("{Client Path}");
var request = new RestRequest(Method.POST);
request.AddHeader("x-rapidapi-host", "{Rapid API host}");
request.AddHeader("x-rapidapi-key", "{My API key}");
request.AddHeader("content-type", "application/json");
request.AddHeader("accept", "application/json");
request.AddParameter("application/json", "{\"url\":\"Image URL\"}", ParameterType.RequestBody);
return await client.ExecuteAsync(request);
}
I've tried these -
Restarting Visual Studio.
Cleaning Temp and prefetch files.

Based on my test, it is the URL encoding that is causing the problem.
You may use the code sample from Rapid API website. However, while using RestClient, you should not urlencode the urlpath. The Rapid API engineer may make a mistake here. In most case, a , character does not need to be urlencoded. So, you can directly use https://microsoft-azure-microsoft-computer-vision-v1.p.rapidapi.com/analyze?visualfeatures=Categories,Tags,Color,Faces,Description as the path string.
And, anyway, the correct encoded string is https://microsoft-azure-microsoft-computer-vision-v1.p.rapidapi.com/analyze?visualfeatures=Categories%2cTags%2cColor%2cFaces%2cDescription
The code sample from Rapid API:
I used the sample, and got the same error message as yours. But I solved it by using the original string or the correct encoded string:
public static async Task<IRestResponse> GetClassifiedImageDataAsync()
{
// The correct encoded string will work
//var client = new RestClient("https://microsoft-azure-microsoft-computer-vision-v1.p.rapidapi.com/analyze?visualfeatures=Categories%2cTags%2cColor%2cFaces%2cDescription");
// The original string will work
var client = new RestClient("https://microsoft-azure-microsoft-computer-vision-v1.p.rapidapi.com/analyze?visualfeatures=Categories,Tags,Color,Faces,Description");
var request = new RestRequest(Method.POST);
request.AddHeader("x-rapidapi-host", "microsoft-azure-microsoft-computer-vision-v1.p.rapidapi.com");
request.AddHeader("x-rapidapi-key", "71a69********************************3ddb");
request.AddHeader("content-type", "application/json");
request.AddHeader("accept", "application/json");
request.AddParameter("application/json", "{\"url\":\"https://upload.wikimedia.org/wikipedia/commons/1/11/Kanye_West_at_the_2009_Tribeca_Film_Festival.jpg\"}", ParameterType.RequestBody);
return await client.ExecuteAsync(request);
}
static void Main(string[] args)
{
var result = GetClassifiedImageDataAsync().GetAwaiter().GetResult();
Console.WriteLine(result.Content);
}
And you can also use RestClient's method to add query string:
public static async Task<IRestResponse> GetClassifiedImageDataAsync()
{
// Without query string
var client = new RestClient("https://microsoft-azure-microsoft-computer-vision-v1.p.rapidapi.com/analyze");
var request = new RestRequest(Method.POST);
// Add as query string manually
request.AddParameter("visualfeatures", "Categories,Tags,Color,Faces,Description", ParameterType.QueryString);
request.AddHeader("x-rapidapi-host", "microsoft-azure-microsoft-computer-vision-v1.p.rapidapi.com");
request.AddHeader("x-rapidapi-key", "71a69********************************3ddb");
request.AddHeader("content-type", "application/json");
request.AddHeader("accept", "application/json");
request.AddParameter("application/json", "{\"url\":\"https://upload.wikimedia.org/wikipedia/commons/1/11/Kanye_West_at_the_2009_Tribeca_Film_Festival.jpg\"}", ParameterType.RequestBody);
return await client.ExecuteAsync(request);
}
And the successful result:

Related

Token Autorization in RestSharp does not appear

Good morning, I'm retrieving an authorization token using RestSharp, but instead of returning a Token, it returns an html page:
var client = new RestClient("https://iam.efatura.cv/auth/realms/taxpayers/ protocol/openid- connect/auth"); var request = new RestRequest(Method.POST); request.AddHeader("grant_type", "authorization_code"); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddHeader("accept", "application/json"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id=adadasdasdasdasda& scope=openid&clientSecretasdadsdadasdasdasdasdasdasdasasd& redirect_uri=https://iam.efatura.cv/auth/realms/taxpayers", ParameterType.RequestBody); IRestResponse response = client.Execute(request); Token=response.Content;

How to transfer trc20 with c#

I couldn't find a c # library for tron. I want to transfer via https://api.trongrid.io api.
There is a helper api tool at https://developers.tron.network/reference#trigger-smart-contract.
However, it is necessary to decode the parameter.
https://developers.tron.network/docs/parameter-and-return-value-encoding-and-decoding
I could not translate the function on the upper link to c #.
Can you help me ?
There is easy transfer method (by password param) and easy transfer (by private key), also documentation has code snippets..
// using rest sharp
var client = new RestClient("https://api.shasta.trongrid.io/wallet/easytransfer");
var request = new RestRequest(Method.POST);
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\"passPhrase\":\"string\",\"toAddress\":\"string\",\"amount\":0}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);

How to capture Json from web site using c#

I have a paid subscription to Seeking Alpha and have a cookkie which enables me to get full data from https://seekingalpha.com/symbol/AAPL/financials-data?period_type=quarterly&statement_type=income-statement&order_type=latest_left&is_pro=True
I'd like to collect JSON response using C#
Below is my horrible code
string cookie = "my super secret cookie string";
var request = new RestRequest(Method.GET);
request.AddHeader("content-type", "application/json");
request.AddHeader("Accept", "*/*");
request.AddHeader("User-Agent","Mozilla/5.0");
request.AddHeader("X-Requested-With", "XMLHttpRequest");
string url = "https://seekingalpha.com/symbol/AAPL/financials-data?period_type=quarterly&statement_type=income-statement&order_type=latest_left&is_pro=True";
request.AddParameter("cookie", cookie, ParameterType.Cookie);
var client = new RestClient(url);
var queryResult = client.Execute(request);
Console.WriteLine(queryResult.Content);
How can I get it to return JSON to me? I am getting something but not the JSON I want
Try updating your Access header to application/json.
request.AddHeader("Accept", "application/json");
Accept indicates what kind of response from the server the client can accept.
You can get more info for Accept from Header parameters: “Accept” and “Content-type” in a REST context
After poking around for a bit I figured it out. For the benefit of all:
private bool FinancialStatement(string symbol, string statement, string period)
{
var target = $"{BASE_URL}{symbol}/financials-data?period_type={period}&statement_type={statement}&order_type=latest_left&is_pro=True";
var client = new RestClient(target);
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("Cookie", MACHINE_COOKIE);
IRestResponse response = client.Execute(request);
dynamic responseObj;
try
{
responseObj = JsonConvert.DeserializeObject(response.Content);
}
catch (Exception)
{
return false;
}
return response.IsSuccessful;
}

RestSharp with JWT

I am trying to create JWT for authenticating REST api. Please find my code below.
private static string getJWT()
{
var client = new RestClient("https://itsmtest-app.XXXXXX.com/api/jwt/login");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("username", "testuser",ParameterType.RequestBody);
request.AddParameter("password", "Passw0rd",ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
return response.Content;
}
I am getting an error. please find response.Content as below. But the rest call working fine in postman even I copied the code postman.
Error 406 Not Acceptable
HTTP ERROR 406
Problem accessing /api/jwt/login.
Reason:Not Acceptable

API REST requests with C#, I hardcoded the URL, but I have several URL on my database that I want to retrieve it from?

This is my API request, I want to get the URL from my database. In here I hardcoded it but I want to make it dynamic, If you can please help me and I will be appreciated.
public static string APICall(string jsonData)
{
var client = new RestClient("https://url.com");
var request = new RestRequest(Method.POST);
//new RestRequest("resource", Method.POST);
request.Parameters.Clear();
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-Type", "application/json");
request.RequestFormat = DataFormat.Json;
// more code...
}

Categories

Resources