I have given below the sample code, I am calling web API but I am struggling to pass the parameter in the console application.
C# code:
HttpClient client = new HttpClient();
var responseTask = client.GetAsync("<web api name>");
responseTask.Wait();
HttpRequestMessage rm = new HttpRequestMessage();
var headers = rm.Headers;
client.DefaultRequestHeaders.Add("client_id", "1234xv");
client.DefaultRequestHeaders.Add("client_secret", "7dfdfsd");
if (responseTask.IsCompleted)
{
var result = responseTask.Result;
if (result.IsSuccessStatusCode)
{
var messageTask = result.Content.ReadAsStringAsync();
messageTask.Wait();
Console.WriteLine("Message from Web API:" + messageTask.Result);
Console.ReadLine();
}
}
You were making the GET call much early, even before adding the parameters to the HTTP headers. You need to add the params and then call the GetAsync().
See the modified code below,
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("client_id", "1234xv");
client.DefaultRequestHeaders.Add("client_secret", "7dfdfsd");
var responseTask = client.GetAsync("http://your api url");
responseTask.Wait();
if (responseTask.IsCompleted)
{
var result = responseTask.Result;
if (result.IsSuccessStatusCode)
{
var messageTask = result.Content.ReadAsStringAsync();
messageTask.Wait();
Console.WriteLine("Message from Web API:" + messageTask.Result);
Console.ReadLine();
}
}
}
Related
I've written the code below in IhttpclientFactory. For some reasons, the code is not returning a token. oauth is returning null.
I will appreciate it if someone would kindly have a look and tell me where I've gone wrong. thank you
private async Task<OAuth>Authenticate()
{
//build request
var request = new HttpRequestMessage(HttpMethod.Post, "/oauth/token");
request.Content = new StringContent(JsonSerializer.Serialize(new OAuth() {grant_type="client_credentials",client_id="",client_secret=""}));
request.Content.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/x-www-urlencoded");
//build client
var client = _clientFactory.CreateClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/+json"));
// send the request
var response = await client.SendAsync(request);
OAuth oauth = null;
if (response.IsSuccessStatusCode)
{
var responseStream = await response.Content.ReadAsStringAsync();
//deserialise
var oAuth = Newtonsoft.Json.JsonConvert.DeserializeObject<OAuth>(responseStream);
}
return oauth;
}
}
You've got two different OAuth variables 'oauth' and 'oAuth'. C# identifiers are case-sensitive.
Should be something like
if (!response.IsSuccessStatusCode)
{
throw new InvalidOperationExeption($"OAuth Request Failed With Status code {response.StatusCode}");
}
var responseString = await response.Content.ReadAsStringAsync();
var oAuth = Newtonsoft.Json.JsonConvert.DeserializeObject<OAuth>(responseString);
return oAuth;
I have an API made in .NET which I am trying to call in my frontend.
The JSON is being generated just fine but the API itself is not being called at all from the cs file code.
public async void createTransaction(String e)
{
Transaction t = new Transaction();
t.EmployeeEmail=e;
t.ManagerEmail="test#test.com";
t.Request="admin";
var json = JsonConvert.SerializeObject(t);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var url = "http://localhost:5001/ssp/addData";
using var client = new HttpClient();
var response = await client.PostAsync(url, data);
string result = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(result);
}
No error is being thrown but the API is not being called also.
But after some time it says TaskCanceledException and I am unable to make any sense of that.
Any kind of help will be greatly appreciated.
using var client = new HttpClient();
var response = await client.PostAsync(url, data);
Should be
HttpResponseMessage response;
using (var client = new HttpClient())
{
response = await client.PostAsync(url, data);
}
Or
var client = new HttpClient();
var response = await client.PostAsync(url, data);
// ...
client.Dispose();
The problem was not at all with code. After hours of debugging found out that the "https" in the API url was required instead of http.
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
// Pass the handler to httpclient(from you are calling api)
var client = new HttpClient(clientHandler)
After adding this everything started working exactly fine.
I'm trying to access a rest endpoint, https://api.planet.com/auth/v1/experimental/public/users/authenticate. It is expecting json in the request body.
I can get the request to work in Postman but not using c#. Using postman I get the expected invalid email or password message but with my code I get "Bad Request" no matter I try.
Here is the code that makes the request
private void Login()
{
try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://api.planet.com/");
client.DefaultRequestHeaders.Accept.Clear();
//ClientDefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
Data.User user = new Data.User
{
email = "myemail#company.com",
password = "sdosadf"
};
var requestMessage = JsonConvert.SerializeObject(user);
var content = new StringContent(requestMessage, Encoding.UTF8, "application/json");
var response = client.PostAsync("auth/v1/experimental/public/users/authenticate", content).Result;
Console.WriteLine(response.ToString());
}
catch (WebException wex )
{
MessageBox.Show(wex.Message) ;
}
}
class User
{
public string email;
public string password;
}
Here are screen grabs form Postman that are working
The way to get this to work was to alter the content header "content-type". By default HTTPClient was creating content-type: application/json;characterset= UTF8. I dropped and recreated the content header without the characterset section and it worked.
content.Headers.Remove("Content-Type");
content.Headers.Add("Content-Type", "application/json");
The issue is you are trying to call an async method without waiting for the response using await method or var task = method; task.Wait() Therefore, when you end up doing response.ToString() it returns the text you are seeing.
One way to handle this within a non-async method would be to do the following:
var task = client.PostAsync("auth/v1/experimental/public/users/authenticate", content);
task.Wait();
var responseTask = task.Content.ReadAsStringAsync();
responseTask.Wait();
Console.WriteLine(responseTask.Result);
Another way is to make the current method async by doing private async void Login() and then do:
var postResp = await client.PostAsync("auth/v1/experimental/public/users/authenticate", content);
var response = await postResp.Content.ReadAsStringAsync();
Console.WriteLine(response);
Create a Method Like this...
static async Task<string> PostURI(Uri u, HttpContent c)
{
var response = string.Empty;
var msg = "";
using (var client = new HttpClient())
{
HttpResponseMessage result = await client.PostAsync(u, c);
msg = await result.Content.ReadAsStringAsync();
if (result.IsSuccessStatusCode)
{
response = result.StatusCode.ToString();
}
}
return response;
}
call In your Method
public void Login()
{
string postData ="{\"email\":\"your_email\",\"password\":\"your_password\"}";
Uri u = new Uri("yoururl");
var payload = postData;
HttpContent c = new StringContent(payload, Encoding.UTF8,"application/json");
var t = Task.Run(() => PostURI(u, c));
t.Wait();
Response.Write(t.Result);
}
Well Im new in Xamarin and I'm developing and App, the authentication is JWT based.
Im using a HttpClient and setting the AuthenticationHeaders but It always returns Unauthorized when I try it on Postman it Works but I can't make it work in my app.
Here is how im trying to do it:
var client = new HttpClient(new HttpClientHandler());
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("JWT", accessToken);
client.BaseAddress = new Uri(urlBase);
var url = string.Format("{0}{1}", servicePrefix, controller);
var response = await client.GetAsync(url);
Try something like this
using (var client = new HttpClient())
{
var uri = new Uri(string.Format($"{<yourURLString>}", string.Empty));
var jsonTransport = "";
var jsonPayload = new StringContent(jsonTransport, Encoding.UTF8, "application/json");
//client.DefaultRequestHeaders.Add("Content-type", "application/json");
client.DefaultRequestHeaders.Add("Authorization", "JWT " + accessToken);
var response = await client.PostAsync(uri, jsonPayload);
string responseContent = await response.Content.ReadAsStringAsync();
}
then deserialize the responseContent to your object using JsonConvert.DeserializeObject
Note: Below are code samples, edit to your own objects
SubscriptionResponse profileResponse = JsonConvert.DeserializeObject<SubscriptionResponse>(responseContent);
then if your method returns something, use the return statement. Something like this
return profileResponse.Data.Subscriptions;
If you're using a get, this could be a guide
var uri = new Uri(string.Format($"{<yourURLHere>}", string.Empty));
client.DefaultRequestHeaders.Add("Authorization", "JWT " + accessToken);
var httpResponse = await client.GetAsync(uri);
var responseContent = await httpResponse.Content.ReadAsStringAsync();
then deserialize your string response
Note: this is a sample - edit to your model (You may use PostMan to get the response format in JSON and model it in C#)
var UserDetailResponse = JsonConvert.DeserializeObject<UserDetail>(responseContent);
return UserDetailResponse;
I have written a following code to perform an XML request using .NET's HttpWebClient library like this:
public async Task<string> DoRequest()
{
using (var httpClient = new HttpClient())
{
string requestXML = "My xml here...";
var request = new HttpRequestMessage(HttpMethod.Post, "example.com");
request.Content = new StringContent(requestXML, Encoding.UTF8, "text/xml");
var response = await httpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
And in the main function of the console application:
Klijent test= new Klijent();
var res = test.DoRequest();
But the res return type is always showing me this:
Id = 1, Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}"
How do I actually perform the request with this library? What am I doing wrong here??
Just simply wait for result
var res = test.DoRequest().Result;
You are expecting immediate result, even though you code is asynchronous.