I'm building an Android app that sends binary data to the server using HttpClient PostAsJsonAsync method. Is is possible to track the progress of the data being sent?
I'm using the code below to send the data to the server:
var client = new HttpClient();
client.BaseAddress = uri;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/bson"));
var result = client.PostAsJsonAsync(uri, fileBytes);
Implement your http post using an AsyncTask. By using this task you can track the progress of the task.
Related
I have the following code as a start to create a API Call to https://jsonplaceholder.typicode.com/posts/. I want to practice making the call, receive a JSON response and then..do stuff.
How can I finish this off to get a response so I can iterate through the response array.
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(URL);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get,"");
request.Content = new StringContent(URL, Encoding.UTF8,"application/json");
Wiring this in VS Code so will need to install packages if needed.
Thank you!
You are almost there. Try (if you want a simple synchronous send):
HttpClient client = new HttpClient();
string responseString;
using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, new Uri("<insert your URL>"))) {
HttpResponseMessage response = client.SendAsync(request).Result;
// Get the response content as a string
responseString = response.Content.ReadAsStringAsync().Result;
}
Note that it's good practice to initialize one instance of HttpClient and reuse it to send multiple requests (rather than initialize one every time you need to send something).
Any headers, URLs and such specific to a message should be set in the HttpRequestMessage class (which should be disposed of with the "using ..." term.
At the moment I am using the following RestSharp request to get a website's content:
var client = new RestClient(productLink);
var request = new RestRequest(Method.GET);
request.AddHeader("Cookie", "insert-cookie-content");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
I have tried converting it into HttpClient as i will need to use the AllowRedirect property later:
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("Cookie", "insert-cookie-content");
var response = await client.GetAsync(productUrl);
Console.WriteLine(response);
The URL I am trying to get a response from is: https://www.nike.com/sg/launch/t/air-max-90-orange-duck-camo
My first problem is that the HttpClient request is giving me 403 Errors whereas the RestClient request was working fine. How can I fix this?
My second problem is that the cookie expires after a couple of uses, and I have to manually get a new one from postman and insert it. Is there anyway for the request to generate its own cookie?
Here is the two fiddler responses compared: https://imgur.com/a/bZo7d9F
In case of HttpClient if you want to pass the Cookies manually through the DefaultRequestHeaders then you have to tell this to the HttpClient to do NOT use CookieContainer. You have to use HttpClientHandler's UseCookie flag to indicate it.
var client = new HttpClient(new HttpClientHandler { UseCookies = false });
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("Cookie", "insert-cookie-content");
var response = await client.GetAsync(productUrl);
Console.WriteLine(response);
I have a WebAPI that sends BASIC authorization information as following.
var client = new HttlpClient();
client.BaseAddress = new Uri(GlobalConstants.LdapUri);
var contentType = new MediaTypeWithQualityHeaderValue("application/json");
client.DefaultRequestHeaders.Accept.Add(contentType);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", userName, password))));
Task<HttpResponseMessage> results = client.GetAsync(GlobalConstants.FortressAPIUriDev);
var response = await results;
I've built this API using MVC Core 1.x and the receiving API is built using MVC5.
The problem is that this GetAsync sends two requests at the same time, and I have no clue how to resolve this. I've done some Googling myself to see if I can find a fix for this but so far no luck. Did anyone experience this problem and know how to resolve it?
Thank you very much in advance.
Long story short, found a solution as follows:
using (var client = new HttpClient())
{
var requestMessage = new HttpRequestMessage(HttpMethod.Get, GlobalConstants.LdapUri + GlobalConstants.FortressAPIUriDev);
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", userName, password))));
var response = await client.SendAsync(requestMessage);
}
After replacing with this code, it is sending one request at a time.
Found a hint at :
Adding headers when using httpClient.GetAsync
When I am making HTTP requests in C# and reading the response, I am getting garbage data in the response. I am unable to figure out the problem. Consider the following example snippet where I make a call to the Stack Exchange API.
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://api.stackexchange.com/info");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("?site=stackoverflow").Result;
if (response.IsSuccessStatusCode)
{
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
}
else
{
Console.WriteLine("Sorry");
}
The screenshot below illustrates the garbage output I am receiving:
I'd appreciate any help in trying to debug this issue and knowing where I went wrong.
The problem is that the data is compressed.
To fix it, without having to decompress the data yourself, instruct HttpClient to do it for you:
HttpClientHandler handler = new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
};
HttpClient client = new HttpClient(handler);
// ... rest of your code here
Your code then gives this output (abbreviated):
{"items":[{"new_active_users":13,"total_users":7599686,"badges_per_minute":5.04,"total_badges":24036822,...
This is also documented:
Additionally, all API responses are compressed.
im using PostAsync to call my external webAPI programatically in my back end.
I have had the method working using a httpget, however turning it into a post seems more problematic, due to the httpcontent object required. when awaiting, the status code is always a 404 due to the data not being passed over.
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:52715/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var data = JsonConvert.SerializeObject(new { user = "JOHNSMITH" });
HttpResponseMessage response = await client.PostAsync("MessageUser", new StringContent(data, Encoding.UTF8, "text/json"));
if (response.IsSuccessStatusCode)
{
Console.WriteLine("\n sent signal to dept");
}
}