This question already has answers here:
How can I call async method from constructor?
(5 answers)
Closed 2 years ago.
I want to parse from a JSON file in a universal windows phone application but I can't convert task to string
public MainPage()
{
this.InitializeComponent();
HttpClient httpClient = new HttpClient();
String responseLine;
JObject o;
try
{
string responseBodyAsText;
HttpResponseMessage response = httpClient.GetAsync("http://localhost/list.php").Result;
//response = await client.PostAsync(url, new FormUrlEncodedContent(values));
response.EnsureSuccessStatusCode();
responseBodyAsText = response.Content.ReadAsStringAsync().Result;
// responseLine = responseBodyAsText;
string Website = "http://localhost/list.php";
Task<string> datatask = httpClient.GetStringAsync(new Uri(string.Format(Website, DateTime.UtcNow.Ticks)));
string data = await datatask;
o = JObject.Parse(data);
Debug.WriteLine("firstname:" + o["id"][0]);
}
catch (HttpRequestException hre)
{
}
I have error in this line
string data = await datatask;
how can I fix it?
Looking into this documentation, you can get that using: Result property.
For Example:
Task<int> task1 = myAsyncMethod(); //You can also use var instead of Task<int>
int i = task1.Result;
You cannot use await inside a constructor. You'll need to create an async method for that.
Generally I don't recommend using async void, but when you're calling it from the constructor it's somewhat justified.
public MainPage()
{
this.InitializeComponent();
this.LoadContents();
}
private async void LoadContents()
{
HttpClient httpClient = new HttpClient();
String responseLine;
JObject o;
try
{
string responseBodyAsText;
HttpResponseMessage response = await httpClient.GetAsync("http://localhost/list.php");
//response = await client.PostAsync(url, new FormUrlEncodedContent(values));
response.EnsureSuccessStatusCode();
responseBodyAsText = await response.Content.ReadAsStringAsync();
// responseLine = responseBodyAsText;
string Website = "http://localhost/list.php";
Task<string> datatask = httpClient.GetStringAsync(new Uri(string.Format(Website, DateTime.UtcNow.Ticks)));
string data = await datatask;
o = JObject.Parse(data);
Debug.WriteLine("firstname:" + o["id"][0]);
}
catch (HttpRequestException hre)
{
// You might want to actually handle the exception
// instead of silently swallowing it.
}
}
Try this:
Task<string> post = postPostAsync("Url", data).Result.Content.ReadAsStringAsync();
post.Result.ToString();
Related
I am unable to get body content in this http client call, because I can't figure out how to get the actual content of the request in this async method.
Here's the async method:
public async Task<HttpResponseMessage> AuthenticateUser(string username, string password)
{
var client = new HttpClient();
var requestUri = new Uri($"{_authorityBaseUrl}/{_tenantID}/oauth2/token");
var authenticationBody = CreatePasswordGrantConsent(username,password);
return await client.PostAsync(requestUri, authenticationBody);
}
Here's the method that I wanna get the body content from
protected void loginBtn_Click(object sender, EventArgs e)
{
AADConnector connector = new AADConnector();
var result = connector.AuthenticateUser("username", "password").Result.Content;
}
I've tried in AuthenticateUser method to change to :
public async Task<string>(string username , string password)
{
...
...
var response = await client.PostAsync(requestUri, authenticationBody);
var contents = await response.Content.ReadAsStringAsync();
return contents;
}
And change in loginBtn_Click to :
AADConnector connector = new AADConnector();
Task<string> result = connector.AuthenticateUser("username","password");
var finalResult = result.Result;
But it just deadlocks and it keeps running forever.
Can you guys explain me why this happens?
Here is how I did it:
public async Task<string> AuthenticateUser(string username, string password)
{
var client = new HttpClient();
var requestUri = new Uri($"{_authorityBaseUrl}/{_tenantID}/oauth2/token");
var authenticationBody = CreatePasswordGrantConsent(username, password);
var response = await client.PostAsync(requestUri, authenticationBody);
var result = await response.Content.ReadAsStringAsync();
return result;
}
AADConnector connector = new AADConnector();
var result = Task.Run(async () => await connector.AuthenticateUser("username", "password"));
try {
result.Wait();
} catch {
}
dynamic data = JObject.Parse(result.Result);
string token = (string)data.access_token;
I need to pass a string value as text in a Post.
I have tried the following
string content = "91237932,xy91856,0,0";
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.PostAsync(ConfigurationManager.AppSettings["AttributesApi"] + $"/api/UserProfiles/UpdateUserProfileFromIAM", new StringContent(content));
This is what I have to work with (can't change it as is existing) but the value is null
[HttpPost("UpdateUserProfileFromIAM")]
public async Task<ActionResult> UpdateUserProfileFromIAM(string attributes)
{
//attributes null
}
How can do this HttpClient post so that it is a simple string value?
If your issue is that you can't read the result then try this:
public async Task<string> GetData()
{
string content = "91237932,xy91856,0,0";
using var client = new HttpClient();
var response = await client.PostAsync(ConfigurationManager.AppSettings["AttributesApi"] + $"/api/UserProfiles/UpdateUserProfileFromIAM", new StringContent(content));
return await response.Content.ReadAsStringAsync();
}
i am trying to call the Zoom Api for Access token. It work Perfectly fine when i am trying to post with postman .
but from code it does not respond
ZoomApiLink_StepNo2
below are the following details
public static async Task<String> PostTogetToken<T>(string requestUrl, string client_Secretkey) {
ZoomToken hello = new ZoomToken();
var EncodedURl = ApiService.Base64Encode(client_Secretkey);
using (var _httpClient = new HttpClient()) {
if (!string.IsNullOrEmpty(requestUrl))
_httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Basic " + EncodedURl);
var httpContent = new StringContent("", System.Text.Encoding.UTF8, "application/x-www-form-urlencoded");
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, new Uri(requestUrl)) {
Version = HttpVersion.Version11,
Content = httpContent
};
using (var response = await _httpClient.SendAsync(httpRequestMessage)) {
if (response.IsSuccessStatusCode) {
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
} else {
return await response.Content.ReadAsStringAsync();
}
}
}
}
You're seeing a common deadlock problem because code further up the stack is using Result, blocking on asynchronous code.
To fix, change the Result to await and use async all the way.
I want to encode the HTML content with UTF-8.
The Code I already have:
public async Task<string> MakeWebRequest()
{
HttpClient http = new HttpClient();
HttpResponseMessage response = await http.GetAsync(**URL**);
return await response.Content.ReadAsStringAsync();
}
Thanks for your help and time.
Dieter
I don't know in which encoding the original string comes but try the following code:
public async Task<string> MakeWebRequest()
{
var http = new HttpClient();
var buffer = await http.GetBufferAsync(**URL**);
var responseString = Encoding.UTF8.GetString(buffer.ToArray(), 0, (int)(buffer.Length- 1));
return responseString;
}
or
public async Task<string> MakeWebRequest()
{
var http = new HttpClient();
var response = await http.GetByteArrayAsync(**URL**);
var responseString = Encoding.UTF8.GetString(response, 0, response.Length - 1);
return responseString;
}
I have a web request that is working properly, but it is just returning the status OK, but I need the object I am asking for it to return. I am not sure how to get the json value I am requesting. I am new to using the object HttpClient, is there a property I am missing out on? I really need the returning object. Thanks for any help
Making the call - runs fine returns the status OK.
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var responseMsg = client.GetAsync(string.Format("http://localhost:5057/api/Photo")).Result;
The api get method
//Cut out alot of code but you get the idea
public string Get()
{
return JsonConvert.SerializeObject(returnedPhoto);
}
If you are referring to the System.Net.HttpClient in .NET 4.5, you can get the content returned by GetAsync using the HttpResponseMessage.Content property as an HttpContent-derived object. You can then read the contents to a string using the HttpContent.ReadAsStringAsync method or as a stream using the ReadAsStreamAsync method.
The HttpClient class documentation includes this example:
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Building on #Panagiotis Kanavos' answer, here's a working method as example which will also return the response as an object instead of a string:
using System.Text;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json; // Nuget Package
public static async Task<object> PostCallAPI(string url, object jsonObject)
{
try
{
using (HttpClient client = new HttpClient())
{
var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json");
var response = await client.PostAsync(url, content);
if (response != null)
{
var jsonString = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<object>(jsonString);
}
}
}
catch (Exception ex)
{
myCustomLogger.LogException(ex);
}
return null;
}
Keep in mind that this is only an example and that you'd probably would like to use HttpClient as a shared instance instead of using it in a using-clause.
Install this nuget package from Microsoft System.Net.Http.Json. It contains extension methods.
Then add using System.Net.Http.Json
Now, you'll be able to see these methods:
So you can now do this:
await httpClient.GetFromJsonAsync<IList<WeatherForecast>>("weatherforecast");
Source: https://www.stevejgordon.co.uk/sending-and-receiving-json-using-httpclient-with-system-net-http-json
I think the shortest way is:
var client = new HttpClient();
string reqUrl = $"http://myhost.mydomain.com/api/products/{ProdId}";
var prodResp = await client.GetAsync(reqUrl);
if (!prodResp.IsSuccessStatusCode){
FailRequirement();
}
var prods = await prodResp.Content.ReadAsAsync<Products>();
What I normally do, similar to answer one:
var response = await httpClient.GetAsync(completeURL); // http://192.168.0.1:915/api/Controller/Object
if (response.IsSuccessStatusCode == true)
{
string res = await response.Content.ReadAsStringAsync();
var content = Json.Deserialize<Model>(res);
// do whatever you need with the JSON which is in 'content'
// ex: int id = content.Id;
Navigate();
return true;
}
else
{
await JSRuntime.Current.InvokeAsync<string>("alert", "Warning, the credentials you have entered are incorrect.");
return false;
}
Where 'model' is your C# model class.
It's working fine for me by the following way -
public async Task<object> TestMethod(TestModel model)
{
try
{
var apicallObject = new
{
Id= model.Id,
name= model.Name
};
if (apicallObject != null)
{
var bodyContent = JsonConvert.SerializeObject(apicallObject);
using (HttpClient client = new HttpClient())
{
var content = new StringContent(bodyContent.ToString(), Encoding.UTF8, "application/json");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
client.DefaultRequestHeaders.Add("access-token", _token); // _token = access token
var response = await client.PostAsync(_url, content); // _url =api endpoint url
if (response != null)
{
var jsonString = await response.Content.ReadAsStringAsync();
try
{
var result = JsonConvert.DeserializeObject<TestModel2>(jsonString); // TestModel2 = deserialize object
}
catch (Exception e){
//msg
throw e;
}
}
}
}
}
catch (Exception ex)
{
throw ex;
}
return null;
}
The code below is to access your HttpResponseMessage and extract your response from HttpContent.
string result = ret.Result.Content.ReadAsStringAsync().Result;
Convert your json in a structure according with your business
In my case BatchPDF is a complex object that it is being populated by result variable.
BatchPDF batchJson = JsonConvert.DeserializeObject<BatchPDF>(result);
return batchJson;