I have a problem with my app in Xamarin Forms.
The GET request works in debug mode but not in release mode.
The POST request works in both mode.
I test on real device and emulator Android.
The api path is HTTPS and the app has INTERNET permission.
This is the code:
if (IsConnected)
{
string jsonRequest = JsonConvert.SerializeObject(request);
StringContent content = new StringContent(jsonRequest, Encoding.UTF8, "application/json");
var Request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri(client.BaseAddress + $"api/Servizi/getServizi"),
Content = content
};
var jsonResponse = await client.SendAsync(Request);//.ConfigureAwait(false);
var contents = await jsonResponse.Content.ReadAsStringAsync();
response = await Task.Run(() => JsonConvert.DeserializeObject<ServiziResponse>(contents));
}
In visual Studio Add this line in Android Options
VS19
Related
I'm basically new to mobile development and stuck for a few weeks because,
I am unable to connect XAMARIN Android app with MQTTT over TLS.
Maybe i am using the wrong library or is it an Xamarin error?
My certificate is a .crt file from m21.cloudmqtt.com.
https://crt.sh/?id=5253106089
First was using System.Net MQTT but they are currently unable to work over TLS.
So i currently i am using MQTTNet, with (for the moment) the default certificate from m21.cloud.com which i have stored in Assets folder.I tested this local with and without a certificate and its working fine.
The MQTTNet Client with cert from local folder is like this, and works like it should:
var caCert = new X509Certificate2("C:/pathtocert.crt");
var source = new CancellationTokenSource().Token;
var token = source;
var factory = new MqttFactory();
var mqttClient = factory.CreateMqttClient();
var mqttOptions = new MqttClientOptionsBuilder()
.WithTcpServer(server, port)
.WithClientId(clientId)
.WithCredentials(username, pswd)
.WithTls(new MqttClientOptionsBuilderTlsParameters
{
UseTls = true,
Certificates = new List<X509Certificate> { caCert }
})
.Build();
mqttClient.ConnectAsync(mqttOptions, token).Wait(token);
To get the Certifcate from Android Assets Folder i used the same client code as above and t et the certificate i used:
using (var assetStream = await Xamarin.Essentials.FileSystem.OpenAppPackageFileAsync("filename.crt"))
using (var memStream = new MemoryStream())
{
assetStream.CopyTo(memStream);
caCert = new X509Certificate(memStream.ToArray());
}
I dont understand why its not working, for now its also okay if the certificate isn't used but it needs to use TLS. But tried, and i still get unauthorized error.
var mqttOptions = new MqttClientOptionsBuilder()
.WithTcpServer(server, port)
.WithClientId(clientId)
.WithCredentials(username, pswd)
.WithTls(new MqttClientOptionsBuilderTlsParameters
{
UseTls = true,
})
.Build();
Thanks in adnvance.
I'm trying to access my web server hosted on http://localhost:8080 on an Angular App built with Cordova. I can access the server with a navigator on my emulator but I never receive any request from the application itself it's just failed with the following error: [objectProgressEvent].
My request is like this and works if I build the web application hosted on localhost:8081:
getToken(username, password) {
var req = { username: username, password: password };
this.http.post(this.urlToken, req).toPromise().then((data) => {
document.getElementById("loader").style.display = "none";
for (let key in data) {
this.token = data[key]
localStorage.setItem('token', this.token);
}
if (void this.getIfActiveUser(username) != 84) {
localStorage.setItem('user', username);
this.authService.login();
}
}).catch((err: HttpErrorResponse) => {
document.getElementById("loader").style.display = "none";
this.getIfActiveUser(username)
console.error('An error occurred:', err.error);
document.getElementById("warning").style.display = "block";
if (err.error["non_field_errors"])
document.getElementById("warning").innerHTML = err.error["non_field_errors"];
if (err.error["username"])
document.getElementById("warning").innerHTML = err.error["username"]
if (err.error["password"])
document.getElementById("warning").innerHTML = err.error["password"]
});
}
Android API doesn't allow clear text communication by default.
(CleartextTrafficPermitted)
You can check this answer to allow it.
we have an app under xamarin android build with visual studio 2017.
this app works since three years without any problems.
since two weeks and I don't know why actually some device can't sync with our back end.
It's really strange because nothing has change in this part .
this error does not appear on all devices but on one or two from time to time
we use the dll httpClient for to sync the datas with our backend.
If i put a break point inside the postAsync I have an exception with this -> Cannot access a disposed object. Object name: 'System.Net.Sockets.NetworkStream
Any one has an idea about how to solve this ? also what does it meam ?
Here is it the code of the postAsync method :
thanks for our time and comment guys
public override HttpResult ExecutePost(Uri target, string body)
{
var client = new HttpClient();
client.MaxResponseContentBufferSize = MaxHttpResponseBufferSize;
try
{
var requestContent = new StringContent(body, RequestContentEncoding, RequestContentType);
var response = client.PostAsync(target, requestContent).Result;
if (response.IsSuccessStatusCode)
{
var content = response.Content.ReadAsStringAsync().Result;
return new HttpResult(content, null, null);
}
return new HttpResult(null, "Response is empty", response.StatusCode.ToString());
}
catch (Exception e)
{
return new HttpResult(null, "Problem with the HttpPost", e.Message);
}
}
I experienced the same issue. Have been battling for 6 hours on this issue.
If you read the error, I was getting (Failed to connect to localhost/127.0.0.1:7113). If you put localhost in your browser or swagger tool it will work but if you put https://127.0.0.1:7113/api/weatherforecast in your browser it will not work. It will give you a certificate problem.
So I think you have to resolve 127.0.0.1 to localhost with https certificate on your local dev machine.
I'm building a MAUI app with Visual Studio 2022 Preview.
So I solved this issue by deploying my API to AZURE.
Then update to the azure url for example:
string apiUrl = "https://weatherforecast.azurewebsites.net/api/weatherforecast";
and then it worked brilliantly. Like super brilliantly.
Here is my code:
public void LoginAsync()
{
HttpClient client = new HttpClient();
string apiUrl = "https://weatherforecast.azurewebsites.net/api/weatherforecast";
UserCredentials.EmailAddress = LoginUIEntity.EmailAddress;
UserCredentials.Password = LoginUIEntity.Password;
string serialized = JsonConvert.SerializeObject(UserCredentials);
var inputMessage = new HttpRequestMessage
{
Content = new StringContent(serialized, Encoding.UTF8, "application/json")
};
inputMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
var message = client.PostAsync(apiUrl, inputMessage.Content).Result;
if (message.IsSuccessStatusCode)
{
var apiResponse = message.Content.ReadAsStringAsync();
UserCredentials = JsonConvert.DeserializeObject<UserCredentials>(apiResponse.Result);
if (UserCredentials.IsValid)
{
UserCredentials.IsLoggedIn = true;
}
else
{
ErrorMessage = "Invalid credentials supplied.";
}
}
}
catch (Exception ex)
{
ErrorMessage = "An error has occurred. Please contact support if the error persists.";
}
}
}
thanks for the link your provide.
I've try up the buffer on the postasync / try to sync in wifi OR 3G / delete special character in json / ...
but nothing work
we have move the prod database to the test and try to sync the data to the test database with postman. with postman the result was ENTITY TOO LARGE !
Json is size > 1.2 mega and the default value inside IIS is set to 1 mega
Here is it the problem ...
thanks problem solve
I've created in Xamarin Forms for iOS a HttpClient function to send a picture from the device to my server. The core function is
var content = new MultipartFormDataContent();
var fileContent = new ByteArrayContent(fileBytes);
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = fName
};
fileContent.Headers.ContentDisposition.Parameters
.Add(new NameValueHeaderValue("userId", UserId.ToString()));
content.Add(fileContent);
using (var client = new HttpClient()) {
client.DefaultRequestHeaders.Add("authenticationToken", SyncData.Token);
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
// more code
}
}
I'm using System.Net.Http. I tried to use the same function for a project in Android but surprisingly it doesn't work. The problem is in the header: if I inspect fileContent I can see every keys but for webapi on the server FileName is not received.
After some logs, I changed this function adding more client.DefaultRequestHeaders like
client.DefaultRequestHeaders.Add("FileName", fName);
Now the webapi receives FileName param.
Now my question is: what did I wrong?
Personally, I use the Add method on MultipartFormDataContent that accepts a filename.
var content = new MultipartFormDataContent();
var fileContent = new ByteArrayContent(fileBytes);
...
// Use the overload Add method which accepts a file name
content.Add(fileContent, "FileName", fName);
...
I'm not sure if this will solve your problem or not, but it works for me.
I am new to Xamarin and C# as well. I try to make a Http request to my server with some information.
In general with android Native a uses AsyncTask and HttpClient for that. and build a json object or name value pair, and encrypt it to integrate information with the request.
But when I try to do the same with xamarin I get some problems.
if I try to import the namespace
using System.Net.Http.HttpClient
than my xamarin not have this namespace
Because of the above problem I try to use HttpWebRequest. But when I go for use it with the asyc and await I am not getting any response from server.
I am new to xamarin so I am not sure about async and await keyword.
I read lot of articles but No luck :(
on Click of the Button I call the below Method
public async Task<int> ValidateUser(){
try{
var request = HttpWebRequest.Create (URL);
request.Method = "GET/POST";
String postString = String.Format ("AAA ={0}&BBB={1}&CCC={2}", "111",
"222","333");
byte[] postByte = Encoding.UTF8.GetBytes (postString);
Stream st = request.GetRequestStream ();
//I am reaching here
Console.WriteLine("Check for Validity");
request.ContentLength = postByte.Length;
st.Write (postByte, 0, postByte.Length);
st.Close ();
Task<Stream> contentTask = request.GetRequestStreamAsync();
Stream response = await contentTask;
String str = response.ToString();
// this is not getting printed in Console
Console.WriteLine("=====>>"+str);
}
catch (WebException exception) {
string responseText;
using (var reader = new StreamReader(exception.Response.GetResponseStream())) {
responseText = reader.ReadToEnd ();
Console.WriteLine ("====Dude Error"+responseText);
}
}catch(Exception e){
}
return 1;
}
Any help will be appreciated
Consider using RestSharp, a component created for Xamarin to facilitate web requests. Click here for more info on the component. It will facilitate allot of things about webrequesting ( like serialization, automatic return type detection,... )
Your code would look something like this with restsharp:
public async Task<int> ValidateUser(){
var client = RestClient (URL);
var request = new RestRequest ("AAA ={0}&BBB={1}&CCC={2}", "111",
"222","333");
client.ExecuteAsync (request, response => {
WebApiResponse webApiResponse = new WebApiResponse ();
webApiResponse.Content = response.Content;
webApiResponse.StatusCode = response.StatusCode;
webApiResponse.ResponseStatus = (WebApiResponseStatus)response.ResponseStatus;
return webApiResponse.Content;
});
return -1
}
Using HttpWebRequest is a bad idea, instead it would be better to focus on why you don't have the System.Net.Http.* namespace. Imho the most likely cause is that you didn't add System.Net.Http as a reference to your project.
Here's how you add System.Net.Http.* to your project.
In Visual Studio 2013:
Open the solution
Open the project
Open the Solution Explorer
Right-click on References
Add Reference
Click on 'Search Assemblies'
Type in 'Http'
Select System.Net.Http
Press 'OK'
In Xamarin Studio:
Open the solution
Open the project
Open the Solution Explorer
Right-click on References
Edit References
Type in 'Http'
Select System.Net.Http
Press 'OK'
Afterwards there should be no problems resolving System.Net.Http when 'using System.Net.Http;'