Face API works with URL of the image but when I try to send image as
Base64 encoded it returns an error.
In this sample code I used Restsharp to send the data
My code is like below.
public string GenerateRest(String Base64Image)
{
var serviceURL = Constants.BaseServiceURI;
var client = new RestClient(serviceURL);
var request = new RestRequest(Constants.BaseResoruce, Method.POST);
request.AddHeader("Ocp-Apim-Subscription-Key", Constants.MS_API_KEY);
request.AddHeader("Content-Type", "application/octet-stream");
request.RequestFormat = DataFormat.Json;
var baseString = Base64Image.Replace("data:image/jpeg;base64,", String.Empty);
byte[] newBytes = Convert.FromBase64String(baseString);
request.AddBody(newBytes);
// execute the request
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
return content;
}
After fixing Restsharp request according to answer code is like
public FaceAPIOutput GenerateRest(String Base64Image)
{
var serviceURL = Constants.BaseServiceURI;
var client = new RestClient(serviceURL);
var baseString = Base64Image.Replace("data:image/jpeg;base64,", String.Empty);
byte[] newBytes = Convert.FromBase64String(baseString);
var request = new RestRequest(Constants.BaseResoruce, Method.POST);
request.AddHeader("Ocp-Apim-Subscription-Key", Constants.MS_API_KEY);
request.AddParameter("application/octet-stream", newBytes, ParameterType.RequestBody);
request.RequestFormat = DataFormat.Json;
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
return ConvertToFaceAPIOutObject(content);
}
Restsharp looks a bit idiosyncratic when taking a binary payload. Instead of request.AddBody, which adds a multipart form section, you need to do the following:
request.AddParameter("application/octet-stream", newBytes, ParameterType.RequestBody);
c.f. Can RestSharp send binary data without using a multipart content type?
Related
I'm new to c# and I'm trying to return the data I get from a restClient to use later in my Program.
public string SlackGet(string parameterJsonObject, string url, string token)
{
var client = new RestClient(url);
var request = new RestRequest(Method.GET);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", $"Bearer {token}");
request.AddParameter("application/json", parameterJsonObject, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
var result =(response.Content);
Console.WriteLine(result);
return(result);
Console.WriteLine($"done!");
}
With this I am recieving the following error 'result' is a variable but is used like a type
What am I doing wrong?
TIA
I'm consuming a Web API of an internal system in the company.
It's getting a payload in JSON format and returning a response with data in JSON format.
When sending the request with Postman, it returns the expected response (StatusCode=200 + a response text in JSON format). That means that everything is OK with the web service.
Now I have to develop an application in C# to send this HTTP request.
The problem is, that I receive as response content "OK" and not the expected JSON response gotten with Postman.
public HttpWebResponse SendRequest(string url, string checkOutFolder, string drawingNo, string login, string password)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/json";
request.Method = "GET";
request.Accept = "application/json";
string payload = GeneratePayLoad(checkOutFolder, drawingNo);
string header = CreateAuthorization(login, password);
request.Headers[HttpRequestHeader.Authorization] = header;
request.ServicePoint.Expect100Continue = false;
var type = request.GetType();
var currentMethod = type.GetProperty("CurrentMethod", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(request);
var methodType = currentMethod.GetType();
methodType.GetField("ContentBodyNotAllowed", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(currentMethod, false);
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(payload);
}
// Response
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader rd = new StreamReader(response.GetResponseStream()))
{
string responseContent = rd.ReadToEnd();
Console.WriteLine(responseContent);
}
return response;
}
Has anyone already experiences something similar.
Can you help me?
EDIT
Following your suggestions
1) Changed the method to POST -> result is still the same
2) Used Postman's code generator and RestSharp -> result is still the same
public void Request(string url, string checkOutFolder, string drawingNo, string login, string password)
{
var client = new RestClient(url);
var request = new RestRequest();
request.Method = Method.Post;
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", "Basic **********");
var body = GeneratePayLoad(checkOutFolder, drawingNo);
request.AddParameter("application/json", body, ParameterType.RequestBody);
var response = client.Execute(request);
Console.WriteLine(response.Content);
}
Changed to HttpClient -> result still the same
using (var client = new HttpClient())
{
string uri = "******************";
string path = "destinationpath";
var endpoint = new Uri(uri);
string payload = GeneratePayLoad(path, "100-0000947591");
//FormUrlEncodedContent form = new FormUrlEncodedContent(payload);
var stringContent = new StringContent(payload);
var payload2 = new StringContent(payload, Encoding.UTF8, "application/json");
var byteArray = Encoding.ASCII.GetBytes("*******");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
var base64EncodedAuthenticationString = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(client.DefaultRequestHeaders.Authorization.ToString()));
var result = client.PostAsync(endpoint, stringContent).Result.Content.ReadAsStringAsync().Result;
Console.WriteLine("test");
}
Wrote a Python code using requests Package -> delivers the same as Postman. So the problem is in the C# code.
Does anyone have an idea what is going on?
SOLVED
The issue was on the payload generation!
The request needs to be an HTTP POST and not HTTP GET because it contains JSON payload.
request.Method = "GET"; should be request.Method = "POST";
That would be one of the issue(s). I am not sure if there is something else that is wrong, but try changing the request method to POST and try again.
I am New in C#.
I want to send JSON request body in POST request using C#.
I want To get results from Rest URL but it's showing me status code 500.
How can I format the request body so that I able to get results from the rest URL?
My Request body in JSON -->
{"filter":{"labtestName":[{"labtestName":"Ada"}]}}
code that I tried
string data1 = "{\filter\":{\"labtestName\":[{\"labtestName\":\"Ada\"}]}}";
var RestURL = "https://nort.co.net/v1api/LabTest/Hurlabtest";
HttpClient client = new HttpClient();
string jsonData = JsonConvert.SerializeObject(data1);
client.BaseAddress = new Uri(RestURL);
StringContent content1 = new StringContent(jsonData, Encoding.UTF8, "application/json");
client.DefaultRequestHeaders.Add("apptoken", "72f303a7-f1f0-45a0-ad2b-e6db29328b1a");
client.DefaultRequestHeaders.Add("usertoken", "cZJqFMitFdVz5MOvRLT7baVTJa+yZffc5eVoU91OqkMYl6//cQmgIVkHOyRZ7rWTXi66WV4tMEuj+0oHIyPS6hBvPUY5/RJ7oWnTr4LuzlKU1H7Cp68za57O9AatAJJHiVPowlXwoPUohqe8Ad2u0A==");
HttpResponseMessage response = await client.PostAsync(RestURL, content1);
var result = await response.Content.ReadAsStringAsync();
var responseData = JsonConvert.DeserializeObject<LabtestResponseData>(result);
You are sending the wrong data to the method,
I have corrected it, you can refer to the below code.
myData string is already a JSON string so there is no need to serialize it again.
string myData = "{\"filter\": {\"labtestName\": [{\"labtestName\": \"Ada\"}]}}";
//string data1 = "{\filter\": {\"labtestName\": [{\"labtestName\": \"Ada\"}]}}";
var RestURL = "https://tcdevapi.iworktech.net/v1api/LabTest/HSCLabTests";
HttpClient client = new HttpClient();
//string jsonData = JsonConvert.SerializeObject(myData);
client.BaseAddress = new Uri(RestURL);
StringContent content1 = new StringContent(myData, Encoding.UTF8, "application/json");
I need to call a Post service with RestSharp
var client = new RestClient(url);
var request = new RestRequest(url,Method.POST);
request.AddHeader("Content-type", "application/json");
request.AddJsonBody(new { grant_type = "client_credentials", client_id = clientIdParam, client_secret = appReg_clientSecret, ressource = _ressource }
);
var response = client.Post(request);
The problem is that the request's body is always null and the json body is added as a parameter
Any ideas?
https://login.microsoftonline.com/{{tenantId}}/oauth2/token
seems to not accept json, even with the content-type set as "application/json"
My solution:
var client = new RestClient("https://login.microsoftonline.com");
var request = new RestRequest("/{{tenantId}}/oauth2/token", Method.POST);
var requestBody = $"grant_type=client_credentials&client_id={clientIdParam}&client_secret={appReg_clientSecret}&resource={_resource}";
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", requestBody, ParameterType.RequestBody);
var response = client.Execute(request);
I'm trying to use RESTSharp to create a simple folder on Box, but I'm having a hard time. I keep getting this error:
{"type":"error","status":400,"code":"bad_request","help_url":"http://developers.box.com/docs/#errors","message":"Could
not parse JSON","request_id":"1474540366505ba7a11bdcd"}
This is my code:
static string box(string resourceURL, string APIKey, string authToken)
{
RestClient client = new RestClient();
client.BaseUrl = "https://api.box.com/2.0";
var request = new RestRequest(Method.POST);
request.Resource = resourceURL;
string Headers = string.Format("Authorization: BoxAuth api_key={0}&auth_token={1}", APIKey, authToken);
request.AddHeader("Authorization", Headers);
request.AddParameter("name", "TestFolder");
// request.RequestFormat = DataFormat.Json;
var response = client.Execute(request);
return response.Content;
}
What am I missing? Thanks in advance for your help.
You may also want to take a look at a recently created github repo, where some folks are collaborating on a C# Box SDK. https://github.com/jhoerr/box-csharp-sdk-v2
I see two issues:
The URL needs to point to /folder/{folder_id} (0 is the id of the root folder)
The folder name needs to be in the json body of the request, not a query parameter
I'm not that familiar with C# or RESTSharp, but I believe this code should address the two problems.
static string box(string APIKey, string authToken)
{
RestClient client = new RestClient();
client.BaseUrl = "https://api.box.com/2.0";
var request = new RestRequest(Method.POST);
request.Resource = "/folders/0";
string Headers = string.Format("BoxAuth api_key={0}&auth_token={1}", APIKey, authToken);
request.AddHeader("Authorization", Headers);
request.AddParameter("text/json", "{\"name\" : \"TestFolderName\"}", ParameterType.RequestBody);
//request.RequestFormat = DataFormat.Json;
var response = client.Execute(request);
return response.Content;
}
Thanks for your help, this is the exact code that finally worked.
static string box(string APIKey, string authToken)
{
RestClient client = new RestClient();
client.BaseUrl = "https://api.box.com/2.0";
var request = new RestRequest(Method.POST);
request.Resource = "/folders/0";
string Headers = string.Format("BoxAuth api_key={0}&auth_token={1}", APIKey, authToken);
request.AddHeader("Authorization", Headers);
request.AddParameter("text/json", "{\"name\" : \"TestFolderName\"}", ParameterType.RequestBody);
//request.RequestFormat = DataFormat.Json;
var response = client.Execute(request);
return response.Content;
}
static string folderCreation(string APIKey, string authToken)
{
RestClient client = new RestClient();
client.BaseUrl = "https://api.box.com/2.0/folders";
var request = new RestRequest(Method.POST);
string Headers = string.Format("Bearer {0}", authToken);
request.AddHeader("Authorization", Headers);
request.AddParameter("application/json", "{\"name\":\"Youka\",\"parent\":{\"id\":\"0\"}}", ParameterType.RequestBody);
var response = client.Execute(request);
return response.Content;
}