Rest POST API working with POSTMAN but not working Xamarin.Forms - c#

Heres the code to my HttpPost request
async void ContinueBtn_Clicked(object sender, EventArgs e)
{
if (!CheckValidation())
{
LoginBLL cust = new LoginBLL();
EncryptPassword encrypt = new EncryptPassword();
cust.name = txtFieldName.Text;
cust.email = txtFieldEmail.Text;
cust.Password = encrypt.HashPassword(txtFieldPass.Text);
cust.profession = txtFieldJob.Text;
cust.company = txtFieldCompany.Text;
cust.subId = 1320;
HttpClient client = new HttpClient();
string url = "https://www.example.com/api/customer/";
var uri = new Uri(url);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response;
var json = JsonConvert.SerializeObject(cust);
var content = new StringContent(json, Encoding.UTF8, "application/json");
response = await client.PostAsync(uri, content);
if (response.StatusCode == System.Net.HttpStatusCode.Accepted)
{
validationName.Text = await response.Content.ReadAsStringAsync();
}
else
{
validationName.Text = await response.Content.ReadAsStringAsync();
}
}
And I am getting this error when I am executing the above function
No HTTP resource was found that matches the request URI 'https://www.example.com/api/customer/'.
But it is working fine in Postman with same variables.
I even verified the JSON generated in POSTMAN with the JSON being generated in the Visual Studio it is identical.
I am running this on iphone 8 iOS 12.0

Related

ASP.NET Web API post to an external api

I would like to ask if it is possible for a created ASP.NET Web API (written in C#) to post to an external API?
If it is possible, please share sample code that can post to an url with adding headers and receive a callback from the external API.
A simple way to make HTTP-Request out of a .NET-Application is the System.Net.Http.HttpClient (MSDN). An example usage would look something like this:
// Should be a static readonly field/property, wich is only instanciated once
var client = new HttpClient();
var requestData = new Dictionary<string, string>
{
{ "field1", "Some data of the field" },
{ "field2", "Even more data" }
};
var request = new HttpRequestMessage() {
RequestUri = new Uri("https://domain.top/route"),
Method = HttpMethod.Post,
Content = new FormUrlEncodedContent(requestData)
};
request.Headers // Add or modify headers
var response = await client.SendAsync(request);
// To read the response as string
var responseString = await response.Content.ReadAsStringAsync();
// To read the response as json
var responseJson = await response.Content.ReadAsAsync<ResponseObject>();
Essentially you need use an instance of HttpClient to send an HttpRequestMessage to an endpoint.
Here is an example to post some jsonData to someEndPointUrl:
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, someEndPointUrl);
request.Headers.Accept.Clear();
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
request.Content = new StringContent(jsonData, Encoding.UTF8, "application/json");
var response = await client.SendAsync(request, CancellationToken.None);
var str = await response.Content.ReadAsStringAsync();
if (response.StatusCode == HttpStatusCode.OK)
{
// handle your response
}
else
{
// or failed response ?
}

HttpClient using Basic authentication

Hi i am trying to call basic authentication in wpf httpclient. however whenever i run the code nothing is showing. Can someone help me why? I am new. Thank you
This is the code:
var userName = "username";
var passwd = "password";
var url = "url";
using var client = new HttpClient();
var authToken = Encoding.ASCII.GetBytes($"{userName}:{passwd}");
client.DefaultRequestHeaders.Authorization = new
AuthenticationHeaderValue("Basic",
Convert.ToBase64String(authToken));
var result = await client.GetAsync(url);
var content = await result.Content.ReadAsStringAsync();
label1.Content = content;
Add content type json since you are returning json. And you have to deserialize your content after receiving
var contentType = new MediaTypeWithQualityHeaderValue("application/json");
client.DefaultRequestHeaders.Accept.Add(contentType);
var response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
var stringData = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<object>(stringData);
// instead of object it is better to use a class you are expecting from request
} else ...error

C# -- Login with Amazon oauth2 -- error when doing POST-request

I am trying to make a POST request to the amazon api to get a token for login with amazon. I am doing this with Xamarin.
What I want is the response from amazon with the token. I tried it according to this tutorial:
Code-Based Linking (CBL) for Amazon Alexa Devices
When using Postman it works fine, I get the right response. When I try to implement this in my Xamarin project I always get the error:
"error_description":"The Content-type is not supported by the authorization server.", "error":"invalid_request"
Here's my code:
client = new HttpClient();
client.BaseAddress = new Uri("https://api.amazon.com/auth/O2/create/codepair");
string contentRaw = "response_type=device_code&client_id=hereIsTheClient_ID&scope=alexa:all";
var content = new StringContent(contentRaw, Encoding.UTF8, "application/x-www-form-urlencoded");
string uriEncoded = Uri.EscapeDataString(contentRaw);
HttpResponseMessage response = await client.PostAsync("https://api.amazon.com/auth/O2/create/codepair", content);
var result = await response.Content.ReadAsStringAsync();
return result;
Here's what I did using JSON, but I still get the "Content-Type is not supported by the authorization server"
O2authRequest o2AuthRequest = new O2authRequest();
o2AuthRequest.response_type = "device_code";
o2AuthRequest.client_id = "amzn1.application-oa2-client....";
o2AuthRequest.scope = "alexa:all";
o2AuthRequest.scope_data = new Scope_Data();
o2AuthRequest.scope_data.productID = "MyAppID";
o2AuthRequest.scope_data.productInstanceAttributes = new Productinstanceattributes();
o2AuthRequest.scope_data.productInstanceAttributes.deviceSerialNumber = "12345";
string contentRaw = JsonConvert.SerializeObject(o2AuthRequest);
var content = new StringContent(contentRaw, Encoding.UTF8, "application/json");
string uriEncoded = Uri.EscapeDataString(contentRaw);
HttpResponseMessage response = await client.PostAsync("https://api.amazon.com/auth/O2/create/codepair", content);
var result = await response.Content.ReadAsStringAsync();

Xamarin Forms - API Post Call not calling

In a Xamarin Form app, from the Master Page menu, in the Portable project, I call Content page InfoScreen into the Detail. InfoScreen code looks something like this:
public InfoScreen()
{
InitializeComponent();
ListAccounts();
}
public void ListAccounts()
{
SearchAccounts SA = new SearchAccounts();
SearchAccountRequest searchAccountRequest = new SearchAccountRequest("000123456789", "","","","");
var searchAccountResult = SA.SearchAccountAsync(searchAccountRequest);
}
Notice that on load it calls ListAccounts, located in a class in the Portable project, which looks as follows:
public async Task<SearchAccountResult> SearchAccountAsync(SearchAccountRequest searchAccountRequest)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:00/api/");
string jsonData = JsonConvert.SerializeObject(searchAccountRequest);
var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
var response = await client.PostAsync("SearchForAccount", content);
var result = response.Content.ReadAsStringAsync().Result;
if (result != "")
{
var sessionResponseJson = JsonConvert.DeserializeObject<SearchAccountResult>(result);
}
However, when var response = await client.PostAsync("SearchForAccount", content); gets hit, it just goes back to InfoScreen and continues to load. The API is never hit, which I'm running locally on debug mode. I tested with Postman and it's working correctly.
I also tried:
var client = new HttpClient();
var data = JsonConvert.SerializeObject(searchAccountRequest);
var content = new StringContent(data, Encoding.UTF8, "application/json");
var response = await client.PostAsync("http://localhost:00/api/SearchForAccount", content);
if (response.IsSuccessStatusCode)
{
var result = JsonConvert.DeserializeObject<SearchAccountResult>(response.Content.ReadAsStringAsync().Result);
}
else
{
//
}
Same results. What am I missing?
Thanks
===============
Tried calling the DEV server, utilizing IP, works fine from Postman. Only thing I'm getting in the app is
Id = 1, Status = WaitingForActivation, Method = {null}

Response content of HttpResponseMessage on making a Post request is always '{}' in uwp

I am making HTTP Post call to a webservice url. In the response I get 200 Status Ok message. But when I try to get the response content using await response.Content.ReadAsStringAsync() its always '{}'. The web service returns either SUCCESS or FAILED based on the user credentials passed. How do I retrieve the message. Please help.
Code to make a web service call
public Task<HttpResponseMessage> PostAsJsonAsync<T>(Uri uri, T item)
{
var client = new HttpClient();
var itemAsJson = JsonConvert.SerializeObject(item);
var content = new StringContent(itemAsJson);
//var content = new FormUrlEncodedContent(itemAsJson);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
client.DefaultRequestHeaders.Accept.Clear();
return client.PostAsync(uri, content);
}
private async void mainPage_Loaded(object sender, RoutedEventArgs e)
{
UserDetails details = new UserDetails()
{
username = composite["username"].ToString(),
userpass = composite["password"].ToString()
};
var response = await PostAsJsonAsync(new Uri("http://ec2-xxxx-.compute-1.amazonaws.com:8080/Sanjeevani/rest/SV/login"), details);
if (response.IsSuccessStatusCode) //I get a 200 code i.e OK
{
string str = await response.Content.ReadAsStringAsync();
if (str == "SUCCESS") //str is always '{}'
{
this.Frame.Navigate(typeof(Dashboard), details);
}
}

Categories

Resources