I am not able to get the response content from API call - c#

I am doing a post request and reading the response as given
var response = client.PostAsync(uriBuilder.Uri.ToString(), Content).Result;
var value = response.Content.ReadAsStreamAsync().Result;
if the result is a proper json string, it populates that in 'value' variable
otherwise it returns empty.
but if run the same in postman or fiddler i get this as response
Is there a way to get this response too?

ReadAsStreamAsync() returns a Task<System.IO.Stream> and not a Task<string>. The json string that you see is probably the debugger showing you the content of the stream.
Consider using ReadAsStringAsync() to get the HTML content :
var response = await client.PostAsync(uriBuilder.Uri.ToString(), Content);
var result = await response.Content.ReadAsStringAsync();

Related

HttpClient c#- how to get dynamic content data?

For example, i need to get price values from https://www.futbin.com/22/sales/415/erling-haaland?platform=pc, that are located on the 'sales-inner' table.
The problem is that HTTP Response returns results without loaded prices.
HttpResponseMessage response = await client.GetAsync("https://www.futbin.com/22/sales/415/?platform=pc");
response.EnsureSuccessStatusCode();
string responseString = await response.Content.ReadAsStringAsync();
How to get these data?
The URL you have mentioned in the question renders the view. To get the actual data you need to check the below URLs. Please note that I have got the below URLs from the debugger window but you can check docs if APIs are already provided.
https://www.futbin.com/22/getPlayerSales?resourceId=239085&platform=pc
https://www.futbin.com/getPlayerChart?type=live-sales&resourceId=239085&platform=pc
public async Task Main()
{
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(#"https://www.futbin.com/22/getPlayerSales?resourceId=239085&platform=pc");
response.EnsureSuccessStatusCode();
string responseString = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseString);
}
You are getting html without results because they are loading the data when the page loads. Open dev tools in your browser and check the network tab, there you'll see that they pull the data from:
https://www.futbin.com/22/getPlayerSales?resourceId=239085&platform=pc
That returns a list of all the prices with dates in json.

API response in XML badly encoded, how to correct/convert the string?

I'm querying certain API with HttpClient that sends XML request and receives XML response.
var response = await this.httpClient.PostAsync(apiUrl, new StringContent(content, Encoding.UTF8, "application/xml")));
var responseXml = await response.Content.ReadAsStringAsync();
However responseXml contains
<errorMessage>Je vyžadována autentizace.</errorMessage>
It's supposed to be Je vyžadována autentizace. Any idea what might be causing this behavior and how to get the correct string out of it?
Spent hours on this and just as I wrote the question I came up with solution.
Had to switch from ReadAsStringAsync() to ReadAsByteArrayAsync() and decode it as UTF8, the response was encoded in ISO-8859-1.
var responseXml = Encoding.UTF8.GetString(await response.Content.ReadAsByteArrayAsync());

Get response body from Flurl HttpResponseMessage

Im making some automatic surveillance for an Rest API im running and i need to retrieve the response body from the HttpResponseMessage object.
Im using Flurl Http: https://flurl.dev/docs/fluent-http/
I know how to retrieve the responsebody by adding ".RecieveSomeForm()" at the end of the http request, but i also need to get the response headers, as the error code from the Rest API is sent back as a header. My problem is that - to my knowledge and what i tried - its only the HttpResponseMessage object that i can retrieve the headers from. So the question is:
How do i get the responsebody out of the HttpResponseMessage while still being able to retrieve the headers for error logging?
using (var cli = new FlurlClient(URL).EnableCookies())
{
//get response body - var is set to string and has only response body
var AsyncResponse = await cli.WithHeader("some header").Request("some end point").AllowAnyHttpStatus().PostJsonAsync(some body).ReceiveString();
Console.WriteLine(AsyncResponse);
//get headers - var is set to HttpResponseMessage
var AsyncResponse = await cli.WithHeader("some header").Request("some end point").AllowAnyHttpStatus().PostJsonAsync(some body);
Console.WriteLine(AsyncResponse.Headers);
}
If I've understood correctly, you want Headers + Response body from a HTTP response.
var response = await cli.WithHeader("some header").Request("some end point").AllowAnyHttpStatus().PostJsonAsync("some body");
var headers = response.Headers; //do your stuff
var responseBody = response.Content != null ? await response.Content.ReadAsStringAsync() : null;
Another option which I personally don't like:
var responseTask = cli.WithHeader("some header", "haha").Request("some end point").AllowAnyHttpStatus().PostJsonAsync("some body");
var headers = (await responseTask).Headers; //do your stuff
var responseBody = await responseTask.ReceiveString();
Unfortunately, Flurl's extension methods can be used on Task, not on HttpResponseMessage. (that's why you have to avoid awaiting in the first line of code)

Getting response header

Used the Flurl to Get response from API.
var response = await url.WithClient(fc)
.WithHeader("Authorization", requestDto.ApiKey)
.GetJsonAsync<T>();
dynamic httpResponse = response.Result;
But I cant able to access httpResponse.Headers
How to access response headers while using GetJsonAsync .
You can't get a header from GetJsonAsync<T> because it returns Task<T> instead of raw response. You can call GetAsync and deserialize your payload at next step:
HttpResponseMessage response = await url.GetAsync();
HttpResponseHeaders headers = response.Headers;
FooPayload payload = await response.ReadFromJsonAsync<FooPayload>();
ReadFromJsonAsync is an extention method:
public static async Task<TBody> ReadFromJsonAsync<TBody>(this HttpResponseMessage response)
{
if (response.Content == null) return default(TBody);
string content = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<TBody>(content);
}
P.S. This is why I prefer and recommend to use raw HttpClient instead of any third-party high-level client like RestSharp or Flurl.
You could also await for the HttpResponseMessage, pick off the .Headers object, then send the completed task to ReceiveJson<T> for deserialization. Here's how to do it without an extension method:
var task = url.GetAsync();
HttpResponseMessage response = await task;
HttpResponseHeaders headers = response.Headers;
//Get what I need now from headers, .ReceiveJson<T>() will dispose
//response object above.
T obj = await task.ReceiveJson<T>();

How to get HttpContent from Request object?

If a caller adds HttpContent:
using (var content = new MultipartFormDataContent())
{
HttpContent additionalContent = StringContent("just a test");
content.Add(additionalContent);
Which is then POST'ed, how does the receiver retrieve this additional content?
I've seen examples where people call Request.Content. However, HttpContent.Current.Request doesn't have a Content object.
The receiver is an [HttpPost] WebAPI.
Use ReadAsMultipartAsync extension method for getting content parts and then ReadAsStringAsync for parsing string content:
var provider = await Request.Content.ReadAsMultipartAsync();
var content = provider.Contents.FirstOrDefault(); //assumed single content part has been sent
if (content != null)
{
var result = await content.ReadAsStringAsync();
}
I think the body of your request is nothing but content of request.
Please cross check using F12 developers tools->Network-> Request's response section or body section.

Categories