I am trying to get the response from an API but I am not getting any luck. I am running a async method using C# ASP.NET, but the info which comes from the response displays status and many things but the real response.
This is my code:
private static async Task PostBasicAsync(CancellationToken cancellationToken)
{
Michael Maik = new Michael();
Maik.name = "Michael";
Maik.id = "114060502";
Maik.number = "83290910";
string Url = "http://my-api.com/testing/give-your-data";
using (var client = new HttpClient())
using (var request = new HttpRequestMessage(HttpMethod.Post, Url))
{
var json = JsonConvert.SerializeObject(Maik);
using (var stringContent = new StringContent(
json,
Encoding.UTF8,
"application/json"))
{
request.Content = stringContent;
using (var response = await client
.SendAsync(request,
HttpCompletionOption.ResponseHeadersRead,
cancellationToken)
.ConfigureAwait(false))
{
response.EnsureSuccessStatusCode();
}
}
}
}
What is wrong with my code?
It should return something like:
{
"message": "Hi Michael we have received your data succesfully!",
"data": {
"name": "Michael",
"id": "114060502",
"number": "83290910"
}
}
After the call response.EnsureSuccessStatusCode() you can do:
string resString = await response.Content.ReadAsStringAsync() to get the actual response body.
Related
I need only the "points": 300 from the below response body.
Here is the body:
{
"channel": "abcd",
"username": "fgh",
"points": 300,
"pointsAlltime": 0,
"watchtime": 0,
"rank": 1
}
The Code:
public async int get_points(string user){
var client = new HttpClient();
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new
Uri("https://api.streamelements.com/kappa/v2/points/abcd/fgh"),
Headers =
{
{ "Accept", "application/json" },
{ "Authorization", "Bearer 123" },
},
};
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
Console.WriteLine(body);
}
}
I need only the points value. - 300
You need to deserialize your string response into JSON and with the help of the property name you need to extract the points value.
Using JObject.Parse(String),
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadAsStringAsync();
JObject jObj = JObject.Parse(result);
Console.WriteLine(jObj["points"]);
}
You can also try the native .NET approach introduced in .NET 6+ versions i.e. JsonNode.Parse(),
var jNode = JsonNode.Parse(result);
Console.WriteLine(jNode["points"]);
How do I pass request content in the HttpClient.GetAsync method? I need to fetch data depending upon request content.
[HttpGet]
public async Task<HttpResponseMessage> QuickSearch()
{
try
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
HttpResponseMessage response =await client.GetAsync("http://localhost:8080/document/quicksearch");
if (response.IsSuccessStatusCode)
{
Console.Write("Success");
}
If you are using .NET Core, the standard HttpClient can do this out-of-the-box. For example, to send a GET request with a JSON body:
HttpClient client = ...
...
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri("some url"),
Content = new StringContent("some json", Encoding.UTF8, ContentType.Json),
};
var response = await client.SendAsync(request).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
If you want to send content, then you need to send it as query string (According to your API route)
HttpResponseMessage response =await client.GetAsync("http://localhost:8080/document/quicksearch/paramname=<dynamicName>¶mValue=<dynamicValue>");
And in API check for "paramName" and "paramValue"
this works for me:
using (var httpClient = new HttpClient())
{
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri("your url"),
Content = new StringContent("your json", Encoding.UTF8, ContentType.Json),
};
using (var response = await httpClient.SendAsync(request))
{
string apiResponse = await response.Content.ReadAsStringAsync();
}
}
EDITED:
This is minor different then #SonaliJain answer above:
MediaTypeNames.Application.Json instead of ContentType.Json
I'm assuming that your "request content" would be POST data, no?
If you're sending it using the standard form content way of doing it, you would first have to build the content:
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("username", "theperplexedone"),
new KeyValuePair<string, string>("password", "mypassword123"),
});
And then submit it using PostAsync instead:
var response = await client.PostAsync("http://localhost:8080/document/quicksearch", content);
Hi all thank you for your comments, i got the solution
[HttpGet]
public async Task<HttpResponseMessage> QuickSearch(HttpRequestMessage Query)
{
Debugger.Launch();
try
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
Console.WriteLine(Query);
HttpResponseMessage response = await client.GetAsync("http://localhost:8080/document/quicksearch/"+ Query.RequestUri.Query);
if (response.IsSuccessStatusCode)
{
Console.Write("Success");
}
else
{
Console.Write("Failure");
}
return response;
}
}
catch (Exception e)
{
throw e;
}
I have an endpoint in my ASP.NET Core 2.1 Controller
[HttpPost]
public async Task<bool> CheckStatus([FromBody] StatusModel model)
{
...code ommited
return true;
}
And I call this endpoint from other place in code like this:
await client.PostAsync('/CheckStatus', payloayd)
How can I retrive a bool value from this request?
Using Newtonsoft.Json, you can read the response of the request and parse it into a bool.
using Newtonsoft.Json;
public async Task<bool> GetBooleanAsync()
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var data = new { };
var url = "my site url";
var payload = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
var req = await client.PostAsync(url, payload);
var response = await req.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<bool>(response);
}
}
UPDATE
Looking back on this from a few years on, this can be simplified without the use of Newtonsoft.Json to read the response, by simply parsing the string data to a boolean.
public async Task<bool> GetBooleanAsync()
{
var data = new { };
var url = "my site url";
var payload = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
using var client = new HttpClient();
var response = await client.PostAsync(url, payload);
var data = await response.Content.ReadAsStringAsync();
return boolean.Parse(data);
}
However, if your boolean value is returned in a JSON object, then Newtonsoft.Json could be used to read that value.
I want to post a message to slack on x channel I need to send the following x parameters how do I send the following parameters to a website
"channel": "XXXXX", "token": "token", "text": "text"
I am coding in c# mvc application.
public async Task<HttpResponseMessage> SendMessageAsync(string message, string channel = null, string userName = null)
{
using (var client = new HttpClient())
{
string url = "https://fake2604.slack.com/api/chat.postMessage?token=myToken&channel=" + channel + "&text=Hello World";
var payLoad = new
{
text = message,
channel,
userName,
};
var serializedPayload = JsonConvert.SerializeObject(payLoad);
var response = await client.PostAsync(url, new StringContent(serializedPayload, Encoding.UTF8, "application/json"));
return response;
}
}
This is not working.It just adds an integration to the channel that I select in the OAuth page which again I got through Add to Slack button.
I suppose the problem is with your webhook url which you are adding some more stuff to that.this code definitely work:
public async Task<HttpResponseMessage> SendMessageAsync(string message)
{
var payload = new
{
text = message,
channel="x",
userName="y",
};
HttpClient httpClient = new HttpClient();
var serializedPayload = serializer.ToJson(payload);
var response = await httpClient.PostAsync("url",
new StringContent(serializedPayload, Encoding.UTF8, "application/json"));
return response;
}
I writing UWP app.
I need to send POST request with json to server
Here is my code for downloading JSON and writing to value:
public async void AllOrders_down()
{
string url = "http://api.simplegames.com.ua/index.php/?wc_orders=all_orders";
var json = await FetchAsync(url);
List<RootObject> rootObjectData = JsonConvert.DeserializeObject<List<RootObject>>(json);
OrdersList = new List<RootObject>(rootObjectData);
}
public async Task<string> FetchAsync(string url)
{
string jsonString;
using (var httpClient = new System.Net.Http.HttpClient())
{
var stream = await httpClient.GetStreamAsync(url);
StreamReader reader = new StreamReader(stream);
jsonString = reader.ReadToEnd();
}
return jsonString;
}
How I need to send POST request with this json to server?
Thank's for help.
Here is an example Post request that I have used in a UWP application.
using (HttpClient httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri(#"http://test.com/");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("utf-8"));
string endpoint = #"/api/testendpoint";
try
{
HttpContent content = new StringContent(JsonConvert.SerializeObject(yourPocoHere), Encoding.UTF8, "application/json");
HttpResponseMessage response = await httpClient.PostAsync(endpoint, content);
if (response.IsSuccessStatusCode)
{
string jsonResponse = await response.Content.ReadAsStringAsync();
//do something with json response here
}
}
catch (Exception)
{
//Could not connect to server
//Use more specific exception handling, this is just an example
}
}
You should be using httpClient.PostAsync().