There is this webservice, which i need to get some information. This webservice has an Authentication Header, and two parameters embedded in the body of the request. I have wrote the method using HttpClient class:
HttpClient httpClient = new HttpClient();
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
HttpRequestMessage request = new HttpRequestMessage();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
request.RequestUri = new Uri("URL");
request.Method = HttpMethod.Post;
request.Headers.Add("AUTHENTICATION_Key", "AUTHENTICATION_VALUE");
request.Content = new StringContent("{\"P1\":\"V1\",\"P2\":\"V2\"}",Encoding.UTF8,"application/json");
HttpResponseMessage response = await httpClient.SendAsync(request);
if (response.StatusCode == HttpStatusCode.OK)
{
var responseString = await response.Content.ReadAsStringAsync();
}
the problem has risen from where the project I need to use, is using DotNet 2.0 and in .Net 2 we cannot use asynchronize therefore I cannot use await and SendAsync() as well as ReadAsStringAsync() another problem is SecurityProtocolType.Tls12 is not available in .Net 2. and Im going to need it to get data from it.
I appriciate the help.
Related
I have a problem about 502 gateway error in my production server.
I try to develop an application which calls azure rest endpoints. I get response with Postman by sending the endpoint which has following documentation:
https://learn.microsoft.com/en-us/rest/api/azure/devops/wit/classification-nodes/get?view=azure-devops-rest-6.0
While Postman or Invoke-RestMethod work well with azure endpoint, but API, developed by me, based on HttpClient/RestSharp give an 502 Bad gateway error. HttpClient code part can be found below:
var personalaccesstoken = "<my-token>";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "<my-email-address>", personalaccesstoken))));
HttpRequestMessage requestMessage = new HttpRequestMessage();
requestMessage.Method = HttpMethod.Get;
requestMessage.RequestUri = new Uri("<my-azure-server-address>/_apis/wit/classificationNodes/Areas?$depth=100");
using (HttpResponseMessage response = client.SendAsync(requestMessage).Result)
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
return responseBody;
}
}
How can I solve the problem or which tool can I use to find the exact problem?
Thank you in advance:
Currently, I need to integrate the CoinGecko API, this is a free API open to the public. (https://www.coingecko.com/api/docs/v3)
The HTTP client sends the request but it never returns a response
string BaseUrl = "https://api.coingecko.com/api/v3";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(BaseUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync("/coins/list");
if (response.IsSuccessStatusCode)
{
var data = await response.Content.ReadAsStringAsync();
var table = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Models.Coins>>(data);
}
The expected result is that it should return the coins list, but it never does.
Change BaseUrl to:
string BaseUrl = "https://api.coingecko.com";
and the GetAsync call to
HttpResponseMessage response = await client.GetAsync("/api/v3/coins/list");
I am working with an API service that requires Content-Type to be set to application/json;charset=UTF-8.
If I make a request without the charset=UTF-8 I get a 406 - Not Acceptable.
I can make a call through Postman setting the Content-Type as required, but if I use my .Net Http Client I get the error:
System.FormatException: 'The format of value
'application/json;charset=UTF-8' is invalid.'
Is there anyway I can work around this validation and force the Http Client to accept the value?
UPDATE:
Here is my latest attempt,it still throws the error.
Body.Headers.ContentType = new MediaTypeHeaderValue("application/json;charset=UTF-8");
UPDATE: Content-Type is indeed an invalid header. The API Developers removed it at our request.
Try to set the property:
new MediaTypeHeaderValue("application/json")
{
CharSet = Encoding.UTF8.WebName
};
Try this one
HttpClient httpClient= new HttpClient();
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json; charset=utf-8");
Not sure if still relevant, but I recently ran into this same issue and was able to solve by setting the header in the following way:
string str = $"application/vnd.fmsstandard.com.Vehicles.v2.1+json; charset=UTF-8";
client.DefaultRequestHeaders.Add("Accept", str);
Try adding double quotes around UTF-8, like this:
Body.Headers.ContentType = new MediaTypeHeaderValue("application/json;charset=\"UTF-8\"");
EDIT:
Ok, try something like this. It's working for me locally with a WebApi I already had handy. Notice there is a header specification for what content-type will be ACCEPTED, and then there is a header for what content-type will be SENT with the request. For this example, both of them are JSON:
public static async Task<string> HttpClient(string url)
{
using(HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders
.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json")); // ACCEPT header
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "");
request.Content = new StringContent("{\"id\" : 1}",
Encoding.UTF8,
"application/json"); // REQUEST header
HttpResponseMessage response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
I only added the authentication header to it and it worked for me. AuthToken is either a string variable or the token itself. I left out the content type header and it just works. Below is the code; Response is a string that has to be serialized to a Jobject.
{
String Response = null;
HttpClient client = new HttpClient(CertByPass());
client.Timeout = TimeSpan.FromMinutes(5);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(AuthToken);
Response = await client.GetStringAsync(url);
}
Try creating a client helper class like:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(whatever your url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
return client;
I am not able to get the data from a php rest api from the .net core console app(the call works fine from POSTMAN). I use below code for basic authentication and looks like it redirects to https://www.thesite.org/login for HttpClient.
Not sure what I am missing.
static async Task<RootObject> GetOrderDataAsync()
{
HttpClient client = new HttpClient();
RootObject result = null;
var byteArray = Encoding.ASCII.GetBytes("username:password");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
client.BaseAddress = new Uri("https://www.thesite.org/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync("orders/processing");
if (response.IsSuccessStatusCode)
{
result = await response.Content.ReadAsAsync<RootObject>();
}
return result;
}
I think when you use AuthenticationHeaderValue you don't need to explicitly convert to a Base64 string. Have you tried:
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "username:password");
I am trying to call a Odata service from the C# application. I have called the rest services before and consumed the responses in the C#, and trying Odata for the first time. Below is the Code I am using
using (var client = new HttpClient())
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
Uri uri = new Uri(BaseURL);
client.BaseAddress = uri;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
var response = client.GetAsync(uri).Result;
var responsedata = await response.Content.ReadAsStringAsync();
I am using the same URL and the credentials in PostMan and it returns the response. But throws error i the code, is there something different we need to follow calling a Odata services.Please help with this
It is recommended to use a library to access OData. There are at least a couple of libraries that you can choose from, such as:
https://www.nuget.org/packages/Microsoft.OData.Client/ (OData v4)
https://www.nuget.org/packages/Microsoft.Data.OData/ (OData v1..3)