I'm using HttpClient in .net 4.5 application to post custom object to Web API service.
Code:
public async Task<HttpStatusCode> Run(Customer customer)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://someaddress.net/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.PostAsJsonAsync("api/TestApi", customer)
}
}
Is there a way to get size of this request before calling PostAsJsonAsync?
Thanks.
Related
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 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 the REST API exposed from IBM TM1 Cognos. Using the HttpWebRequest object. Getting the 401 when i tried to pass Authorization header with base64(user:password:namespaceId).
using (var client = new HttpClient())
{
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes("username:password:camnamespace");
var encodeData= System.Convert.ToBase64String(plainTextBytes);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", "CAMNamespace "+ encodeData);
//GET Method
HttpResponseMessage response = await client.GetAsync("http://serveraddress/api/v1/Cubes");
if (response.IsSuccessStatusCode)
{
var det = await response.Content.ReadAsStringAsync();
}
else
{
Console.WriteLine("Internal server Error");
}
}
I think you need something like in payton: verify=False to trust the certificate of response.
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)
I have a functioning async Task that calls a web service:
private async Task GetResult()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(_baseAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Username", _username);
client.DefaultRequestHeaders.Add("Action", "GET");
/* etc */
var response = await client.GetAsync(client.BaseAddress);
}
}
I would like to separate out the creation of the HttpClient object so it can be parameterized and reused:
private async Task GetResult()
{
using (var client = GetClient(_baseAddress, _username))
{
var response = await client.GetAsync(client.BaseAddress);
}
}
private static HttpClient GetClient(string Address, string Username)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(Address);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Username", Username);
client.DefaultRequestHeaders.Add("Action", "GET");
/* etc */
return client;
}
}
While this appears functionally identical to me, the latter throws an AggregateException error with inner exception
Cannot Access a disposed object. Object name: 'System.Net.Http.HttpClient'.
Perhaps there is some async subtlety that I don't understand?
Get rid of the using inside of GetClient. You only use using for things that remain "in your ownership", you are "giving up ownership to the caller" when you return client;.
It is now the caller's resposability to use a using statement (which you do already correctly do in GetResult).
This has nothing to do with asnyc and is simply standard IDisposable behavior.