I am writing an Xamarin.Android app that posts data to Net Core web app with ADAL authentication. The problem is that the API controller is set so it does not require authentication ([AllowAnonymous]), but one and only one of my httpClient.PostAsync() methods responds with the Microsoft Login page. I have tried to use WebClient.UploadString() and the response is the same Login page. I am porting this app from UWP and the same code works there without any problem.
Edit:
Adding some code for more information. The problem is that response.IsSuccessStatusCode is true, but the responseString contains the Microsoft Login page, but it should come back with json data.
HttpResponseMessage response;
try
{
response = await httpClient.PostAsync(url, new System.Net.Http.StringContent(JsonConvert.SerializeObject(data), System.Text.Encoding.UTF8, "application/json"));
}
catch (Exception ex)
{
return result;
}
if (response.IsSuccessStatusCode)
{
var responseString = await response.Content.ReadAsStringAsync();
try
{
//parsing the response
}
catch (Exception)
{
//response was incorrect
}
}
Try this :
HttpContent content = response.Content;
var json = await content.ReadAsStringAsync();
Related
I use xamarin forms to create an mobile app for Android and iOS. I need to make Http Request, so I use HttpClient.
Here is a simple code of request :
var client = new HttpClient();
try
{
string requestUrl = URL_DATABASE + "xxx";
var content = new StringContent("{\"param\":\"" + param+ "\"}", Encoding.UTF8, "application/json");
var response = await client.PostAsync(requestUrl, content);
if (response.StatusCode == HttpStatusCode.OK)
{
var result = await response.Content.ReadAsStringAsync();
return result;
}
return "{\"status\":-1}";
}
catch (Exception ex) // Error catched : "the request timed out"
{
return "{\"status\":-1}";
}
I used Postman to check result of my request and work's well, I got good response without timeout.
I noticed that error occurs sometimes but can last an hour.
error : the request timed out
Thank you in advance for your help
I'm trying to access/call methods in a REST API with a token from c#/.net- but I can't get any response back. I have googlet a lot - but without any success :-( I am new to call methods via a REST API.
I have an endpoint and a token which I need to use for communicating with a REST API. And I need to GET, POST, PUT and DELETE data on the server via those methods
The output from the API is in JSON format.
Maybe it is simple - but I don't know howto do it.
Any help is appreciated.
I have tried the following solution - but with no success :-(
private static async void DoIt()
{
using (var stringContent = new StringContent("{ \"firstName\": \"Andy\" }", System.Text.Encoding.UTF8, "application/json"))
using (var client = new HttpClient())
{
try
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", token);
// 1. Consume the POST command
var response = await client.PostAsync(endpoint, stringContent);
var result = await response.Content.ReadAsStringAsync();
//Console.WriteLine("Result from POST command: " + result);
// 2. Consume the GET command
response = await client.GetAsync(endpoint);
if (response.IsSuccessStatusCode)
{
var id = await response.Content.ReadAsStringAsync();
//Console.WriteLine("Result from GET command: " + result);
}
}
catch (Exception ex)
{
//Console.ForegroundColor = ConsoleColor.Red;
//Console.WriteLine(ex.Message);
//Console.ResetColor();
}
}
}
In your code you initialize AuthenticationHeaderValue with "Basic", which means Basic authentication based on username and password. If you have a token, you do it with:
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", ACCESS_TOKEN);
replace ACCESS_TOKEN with the token you have.
This is the most probable solution, but I can only guess here, as I don't know the API you're trying to access. If it still doesn't work, try ommiting "Bearer".
Reference
I have a standard .net2.0 Xamarin forms project that works flawlessly with the asp.net core webapi as long as I start the api from a different VS2017 instance.
If I include it in the Xamarin solution like this:
It erros out with: Message "Cannot access a disposed object.\nObject name: 'System.Net.Sockets.NetworkStream'." string
This is the http call:
public static async Task<string> PostDataAsync(string url, string json, string baseUrl)
{
try
{
var response = await client.PostAsync(baseUrl + url, new StringContent(
json,
Encoding.UTF8,
"application/json"));
if (response.IsSuccessStatusCode)
{
string result = await response.Content.ReadAsStringAsync();
return result;
}
else
{
return response.ReasonPhrase;
}
}
catch (Exception e)
{
return null;
}
}
It hits the PostAsync methods, the parameters are correct, but goes immediately to "Catch" with the error mentioned above.
Any ideas?
I have a WebAPI service running on a server, and I am able to hit against it all day long in an MVC app I have. I am now trying to create an Xamarin Android app that also hits against the same WebAPI. I put together some code in a console app to test, and it works just fine. However, when I put the same code in my Xamarin Android app, it cannot connect to the service, I get back an aggregate exception that basically wraps a WebException. Digging into the exception further, it seems it is a System.Net.WebExceptionStatus.ConnectFailure type of error.
Here is the code:
using (HttpClient webAPI = new HttpClient())
{
// hardcode the request to try and see why it errors
AuthUserRequest thisUser = new AuthUserRequest
{
UserName = "username",
Password = "password",
AppName = "Dashboard"
};
webAPI.MaxResponseContentBufferSize = 256000;
string json = Newtonsoft.Json.JsonConvert.SerializeObject(thisUser);
var content = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response;
try
{
response = await webAPI.PostAsync("It'sOurURL", content);
}
catch (Exception err)
{
string sHold = err.Message;
throw;
}
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
Context thisContext = Application.Context;
Toast toast = Toast.MakeText(thisContext, "Successful", ToastLength.Short);
toast.Show();
}
}
As I said it's weird it works just fine from a Console app, just not the Xamarin Android app. Any insight at all into this?
All looks pretty good. My API calls are working in Xamarin Android and iOS. My code is pretty much the same with two real minor differences. I have set ConfigureAwait(false) on the PostAsync call. Additionally I have created a URI variable with the address for the API endpoint and passed that into the PostAsync method, rather then using a hard coded string.
using (var client = new HttpClient())
{
var user = new CredentialsModel
{
Password = password,
Username = username,
};
var uri = new Uri("YOUR_URL_GOES_HERE");
var json = JsonConvert.SerializeObject(user);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync(uri, content).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
var responseContent = await response.Content.ReadAsStringAsync();
var authData = JsonConvert.DeserializeObject<ResponseModel>(responseContent);
return authData;
}
return null;
}
It was my own bone-headed mistake... When I tried the URL this morning, it was there, but the IT department has been mucking about with the server, so it's no longer available externally. Sorry to bother everyone with this.
I am trying to access a html page to scrape data from my Windows Phone 8. But first i need to send log-in credentials to it. I am currently using htmlAgilityPack to scrape the data from the login page. I have tried to use WebBrowser instance to run in the background, but the html page is not automatically clickable and i cannot proceed. After which i tried to use the HttpClient class to send data using PostAsync() method, which only recieves a HttpResponseMessage, with which i have no clue what to do, but i am successfully able to send the credential data using a HttpContent object.
var httpResponseMessage = await client1.PostAsync("https://www.webpage.com", content);
After that i have been massively unsuccessful in progressing forward.
Thank you in advance for any help.
Here's how I use HttpClient class to communicate with a webservice in my project:
public async Task<string> httpPOST(string url, FormUrlEncodedContent content)
{
var httpClient = new HttpClient(new HttpClientHandler());
string resp = "";
HttpResponseMessage response = new HttpResponseMessage();
response = await httpClient.PostAsync(url, content);
try
{
response.EnsureSuccessStatusCode();
Task<string> getStringAsync = response.Content.ReadAsStringAsync();
resp = await getStringAsync;
}
catch (HttpRequestException)
{
resp = "NO_INTERNET";
}
return resp;
}
Here you can see how to retrieve the data. Hope it helps :)