consuming API httpClient - asp.net

I am getting error "Bad Request" trying to consum an API. I had tryed some diferents ways, but without success. Could some one help?
API Parameters must be:
FormData Parameters
scope = "oob"
grant_type = "client_credentials"
Header Parameters
Content-type = "application/x-www-form-urlencoded"
Authorization = "Basic 2xpZW50LTAxOnNlY3JldC1rZXktMDI=" (Base64 example)
[POST]
curl -X POST \
https://api-sandbox.getnet.com.br/auth/oauth/v2/token \
-H 'authorization: Basic 2xpZW50LTAxOnNlY3JldC1rZXktMDI=' \
-H 'content-type: application/x-www-form-urlencoded' \
-d 'scope=oob&grant_type=client_credentials'
string content_type = "application/x-www-form-urlencoded";
string scope = "oob";
string grant_type = "client_credentials";
string authorization = "Basic 2xpZW50LTAxOnNlY3JldC1rZXktMDI="
using (var httpClient = new HttpClient())
{
var requestMessage = new HttpRequestMessage()
{
Method = new HttpMethod("POST"),
RequestUri = new Uri("https://api-sandbox.getnet.com.br/auth/oauth/v2/token"),
Content = new StringContent(
#"{""scope"":""oob"",""grant_type"":client_credentials}", Encoding.UTF8, content_type)};
requestMessage.Content.Headers.ContentType =
new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
requestMessage.Headers.Add("Authorization", authorization);
var response = await httpClient.SendAsync(requestMessage);
var responseStatusCode = response.StatusCode;
var responseBody = await response.Content.ReadAsStringAsync();
}

You can try following code snippets
string content_type = "application/x-www-form-urlencoded";
string scope = "oob";
string grant_type = "client_credentials";
string authorization = "Basic 2xpZW50LTAxOnNlY3JldC1rZXktMDI=";
using (var httpClient = new HttpClient())
{
var parameters = new List<KeyValuePair<string, string>>() {
new KeyValuePair<string, string>("scope", "oob"),
new KeyValuePair<string, string>("grant_type", "client_credentials")
};
var requestMessage = new HttpRequestMessage()
{
Method = new HttpMethod("POST"),
RequestUri = new Uri("https://api-sandbox.getnet.com.br/auth/oauth/v2/token"),
Content = new FormUrlEncodedContent(parameters)
};
requestMessage.Content.Headers.ContentType =
new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
requestMessage.Headers.Add("Authorization", authorization);
var response = await httpClient.SendAsync(requestMessage);
var responseStatusCode = response.StatusCode;
var responseBody = await response.Content.ReadAsStringAsync();
}

Related

How can I pass header and parameter with HttpClient in .NET Core

This is my code using the RestSharp library:
var client = new RestClient("https://example.com/api");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer token...");
request.AddHeader("Content-Type", "text/plain");
request.AddParameter("text/plain", "{{\"post\":{{\"contact\":{{\"isActive\":true,\"phone\":\"99999999\"}}", ParameterType.RequestBody);
IRestResponse response = await client.ExecuteAsync(request);
// Console.WriteLine(response.Content);
// var res = response.Content;
How can I convert it to HttpClient using best practices?
You can use this:
var client = new HttpClient()
{
BaseAddress = new Uri("https://example.com"),
Timeout = TimeSpan.FromMinutes(5) //default is 90 seconds
};
client.DefaultRequestHeaders.Add("Authorization", "Bearer token...");
var body = new StringContent("{{\"post\":{{\"contact\":{{\"isActive\":true,\"phone\":\"99999999\"}}",Encoding.UTF8, "text/plain");
var response = await client.PostAsync("api", body);
var responseString = await response.Content.ReadAsStringAsync();
And for using the HttpClient in the right way I highly recommend to see this link.

CSOD Unauthorized Exception:Check your credentials

Trying to access Cornerstone list of employees, but getting this error message.
CSOD Unauthorized Exception:Check your credentials
var client = new RestClient("https://xxx.csod.com/services/api/x/users/v1/employees");
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id=xxx&client_secret=xxx", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
My account has permissions to edit and view Employee API. What else could be the problem.
I had the wrong access point:
var client = new RestClient("https://xxx.csod.com/services/api/oauth2/token");
using Newtonsoft.Json.Linq;
using RestSharp;
using System;
namespace TestAPI
{
class Program
{
static void Main(string[] args)
{
String id = "xxx";
String secret = "xxx";
var client = new RestClient("https://xxx.csod.com/services/api/oauth2/token");
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&scope=all&client_id=" + id + "&client_secret=" + secret, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
dynamic resp = JObject.Parse(response.Content);
String token = resp.access_token;
client = new RestClient("https://xxx.csod.com/services/api/x/users/v1/employees");
request = new RestRequest(Method.GET);
request.AddHeader("authorization", "Bearer " + token);
request.AddHeader("cache-control", "no-cache");
response = client.Execute(request);
}
}
}

How to add two authorization headers in HttpClient

I need to add two header of Authorization in HttpClient as below:
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "XYZNQVJJTkFQUDpX...=");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwToken);
But it seems the last one will override the first one.
I need the Basic and Bearer token. Bearer token for me to pass through the Proxy server which host the SAP WebService, the Basic token for the SAP server. In this case, what I should do?
Update:
How to compose 2 HttpRequestMessage?
string webServiceUrl = "https://adfs.xxx.xxx/";
string strURL = "https://xxx.xxx.xxx/";
HttpResponseMessage responseMessage;
HttpClient client = new HttpClient();
//--1st HttpRequestMessage
var tokenRequest = new HttpRequestMessage(HttpMethod.Post, strURL);
tokenRequest.Headers.Authorization = new AuthenticationHeaderValue("Basic", "XYZNQVJJTkFQUDpX...=");
HttpContent httpContent = new FormUrlEncodedContent(
new[]
{
new KeyValuePair<string, string>("grant_type", "xxx"),
new KeyValuePair<string, string>("client_id", "xxx"),
new KeyValuePair<string, string>("scope", "xxx"),
new KeyValuePair<string, string>("assertion", Base64Assertion)
});
tokenRequest.Content = httpContent;
var tokenResponseMessage = await client.SendAsync(tokenRequest);
var token = await tokenResponseMessage.Content.ReadAsStringAsync();
//-- 2nd HttpRequestMessage
var serviceRequest = new HttpRequestMessage(HttpMethod.Get, webServiceUrl);
serviceRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
var serviceResponseMessage = await client.SendAsync(serviceRequest);
In this case, what I should do?
You will need two separate clients, each with their own default authorization header,
client1.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "XYZNQVJJTkFQUDpX...=");
client2.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwToken);
or one client with no default and the authorization set per request.
For example
var tokenRequest = new HttpRequestMessage(HttpMethod.Post, authServerUrl);
tokenRequest.Headers.Authorization = new AuthenticationHeaderValue("Basic", "XYZNQVJJTkFQUDpX...=");
var httpContent = new FormUrlEncodedContent(
new[]
{
new KeyValuePair<string, string>("grant_type", "xxx"),
new KeyValuePair<string, string>("client_id", "xxx"),
new KeyValuePair<string, string>("scope", "xxx"),
new KeyValuePair<string, string>("assertion",Base64Assertion)
});
tokenRequest.Content = httpContent;
var tokenResponseMessage = await client.SendAsync(tokenRequest);
var token = await responseMessage.Content.ReadAsStringAsync();
var serviceRequest = new HttpRequestMessage(HttpMethod.Get, webServiceUrl);
serviceRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
var serviceResponseMessage = await client.SendAsync(serviceRequest);
//...
It has to do more with HTTP.Its not possible to send through multiple Authentication headers

Debug HttpClient request

How can i see exactly what the request sent by the HttpClient will contain?
var httpClient = new HttpClient();
var postData = JsonConvert.SerializeObject(
new
{
merchantId = _merchantId,
amount = _amount,
paymentRef = _paymentRef,
customer_ref = _customer_ref,
successUrl = _successUrl,
error_url = _error_url,
currency = _currency,
hash = "fsdfsdfsdf"
});
HttpResponseMessage response = await httpClient.PostAsync(url, new StringContent(postData));

I'm new to Json rest full services , how to get methods from json rest service? and how to Parse values to method in api using C# console applications

static void Main(string[] args)
{
const string url = "https://test-api.abccc.com/api/Relayxxx.apixxxx?__token=xxxxxxxxxxxxxxxxxx";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
/* using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"user\":\"xxxx\"," +
"\"password\":\"yyyy\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}*/
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
Please help me how to call functions using this api and how can i get values from specified functions and send values to specific function.

Resources