Calling web api from xamarin android app - android

I have an MSSQL database and a web api over it.
I can call the api from another pc in the same network with the server ip address, so the IIS Express config allows the connection, the firewall is open and the api is working.
I can call an open weather api from the android app, so my code is working.
But from the android app, when I call my web api, it throws timeout exception.
My client code is:
private async Task<string> FetchWebApiHttpClient(string baseUrl, string path)
{
HttpClient client = new HttpClient();
string result = "";
client.BaseAddress = new Uri(baseUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(path);
if (response.IsSuccessStatusCode)
{
result = await response.Content.ReadAsStringAsync();
}
return result;
}
What can be the problem?

Related

XF 504 on Get request when using Android HttpClient implementation

In my Xamarin Forms app I have a very basic GET request that results in a 504 'Method not allowed' on Android.
This is the controller that I am calling:
[AllowAnonymous]
[HttpGet]
[Route("api/system/backendversion")]
public int GetBackendVersion()
{
return 20200924;
}
This is the code that performs the request
var _client = new HttpClient();
var content = new StringContent(json, Encoding.UTF8, "application/json");
var httpRequest = new HttpRequestMessage(httpMethod, url)
{
Content = content,
Version = HttpVersion.Version10
};
var response = await _client.SendAsync(httpRequest);
The problem disappears when I change the HttpClient implementation from "Android" to "Managed".
Also the webrequest works fine in the XF.UWP version of my app.
I believe I put it on Android for a reason, but I'm unsure what the reason was (probably speed). I'm curious what goes wrong here.
Apperantly it breaks because the content (header?) is set to json when there is no json.
I fixed it like this:
var httpRequest = new HttpRequestMessage(httpMethod, url)
{
Version = HttpVersion.Version10
};
if (!string.IsNullOrWhiteSpace(json))
{
httpRequest.Content = new StringContent(json, Encoding.UTF8, "application/json");
}
var response = await _client.SendAsync(httpRequest);
this error is similar to iOS where you get an error if you put json body in a get request
if (httpMethod == HttpMethod.Get && !string.IsNullOrWhiteSpace(json))
{
Debugger.Break();//a get request with a body is not allowed on iOS and results in a error https://stackoverflow.com/questions/56955595/1103-error-domain-nsurlerrordomain-code-1103-resource-exceeds-maximum-size-i
}

Connecting SQL Server database and Xamarin Android using Web API

localhost is not working, I am using a SQL Server database now, but I don't know what to put in localhost IP, I tried 10.0.2.2 and my ipv4 ip. it doesn't work too.
HttpClient client = new HttpClient();
string url = $"https://localhost:xxxxx/api/Feedback?email={feedback.Email}&subject={feedback.Subject}&message={feedback.Message}";
Exception
System.Net.WebException: 'Failed to connect to localhost/127.0.0.1:44330'
Code:
btnSend.Click += async delegate
{
Feedback feedback = new Feedback();
feedback.Email = edtEmail.Text;
feedback.Subject = edtSubject.Text;
feedback.Message = edtMessage.Text;
HttpClient client = new HttpClient();
string url = $"https://localhost:xxxxxx/api/Feedback?email={feedback.Email}&subject={feedback.Subject}&message={feedback.Message}";
var uri = new Uri(url);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response;
var json = JsonConvert.SerializeObject(feedback);
var content = new StringContent(json, Encoding.UTF8, "application/json");
response = await client.PostAsync(uri, content);
Clear();
if (response.StatusCode == System.Net.HttpStatusCode.Accepted)
{
Toast.MakeText(this, "Your Feedback is Saved ", ToastLength.Long).Show();
}
else
{
Toast.MakeText(this, "Your Feedback is not Saved", ToastLength.Long).Show();
}
};
}
Image of WebAPI:
Contents of WebAPI
It Depends on your Dev environment setup, if you are using a real phone then you have to make sure that your PC and your phone are on the same network and the corresponding port number is open in your PC firewall elsewhere the phone can't reach the service.

Receiving a json from an API on Flutter app

I'm trying to receive the response on a http post but the response comes empty. I know its something basic but i can't make it work.
It should receive a JSON with some data, but the data doesn't come, probably its a problem on the reply part on my code.
Heres the code:
Future<void> _login2() async {
HttpClient client = new HttpClient();
client.badCertificateCallback =
((X509Certificate cert, String host, int port) => true);
String url = 'https://sistema.hutransportes.com.br/api/login.php';
Map map = {"user": "test", "pass": "123456"};
HttpClientRequest request = await client.postUrl(Uri.parse(url));
request.headers.set('content-type', 'application/json');
request.add(utf8.encode(json.encode(map)));
HttpClientResponse response = await request.close();
String reply = await response.transform(utf8.decoder).join();
print(reply); //should show the data from the http
}
I would recommend you to use the powerful library https://pub.dev/packages/dio

how to call a route of node server from android app

I am working on android for the first time, I just want to connect my android app with node server on a button click. my node server is
running on localhost and my mobile is also connected to the same
network. can it be possible to connect my android app with running
node server. what i have to do to call a route of server that only
prints "Hello world" in console.log of server.
If possible please help me with the code.
Thanks.
**This is my ooClick function in android.**
public void sendMessage(View view) {
name = (EditText)findViewById(R.id.name);
email = (EditText)findViewById(R.id.email);
phone = (EditText)findViewById(R.id.phone);
address = (EditText)findViewById(R.id.address);
try {
String nme = URLEncoder.encode(name.getText().toString(), "UTF-8");
String eMail = URLEncoder.encode(email.getText().toString(), "UTF-8");
String ph = URLEncoder.encode(phone.getText().toString(), "UTF-8");
String add = URLEncoder.encode(address.getText().toString(), "UTF-8");
// Create http client object to send request to server
HttpClient Client = new DefaultHttpClient();
// Create URL string
String URL = "http://192.168.0.183:3000/save?text1="+nme+"&text2="+eMail+"&text3="+ph+"&text4="+add;
//Toast.makeText(getBaseContext(),"Please wait, connecting to server."+URL,Toast.LENGTH_LONG).show();
try
{
String SetServerString = "";
// Create Request to server and get response
HttpGet httpget = new HttpGet(URL);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
SetServerString = Client.execute(httpget, responseHandler);
// Show response on activity
//content.setText(SetServerString);
Toast.makeText(getBaseContext(),"response"+SetServerString,Toast.LENGTH_LONG).show();
}
catch(Exception ex)
{
Toast.makeText(getBaseContext(),"fail",Toast.LENGTH_LONG).show();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
Toast.makeText(getBaseContext(),"response",Toast.LENGTH_LONG).show();
}
**This is my function in node server**
app.get('/save', function(req, res){
var text1= req.param('text1');
var text2= req.param('text2');
var text3= req.param('text3');
var text4= req.param('text4');
console.log(text1+' '+text2+' '+text3);
});
I just want to print the texts in console.
You should look into using the Retrofit library. This makes it very easy to make HTTP calls from and Android app. Also, you will need the external IP address or server name in order to access the data over your network. "localhost" always refers to the current machine where the software is running. For your desktop, "localhost" is the desktop; for your Android device, "localhost" is the Android device.

Xamarin Android Rest API to PassSlot - nameResolutionFailure

I'm using a REST API to access PassSlot in an attempt to generate a pass / coupon. It seems that when i run the program i get the error: "Error: NameResolutionFailure".
I have:
public static async Task<string> SendAndReceiveJsonRequest()
{
string responseStr = null;
string uri = "https://api.passslot.com/v1/templates/my-template-ID/pass";
// Create a json string with a single key/value pair.
var json = new JObject (new JProperty ("lastName", lastName),
new JProperty ("firstName", firstName),
new JProperty ("percentOff", percentOff),
new JProperty ("offerDescription", offerDescription),
new JProperty ("entityName", entityName),
new JProperty ("expiry", expiry));
//Console.WriteLine ("Jake's JSON " + json.ToString ());
using (var httpClient = new HttpClient ())
{
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("My-Key-Here-xxx-xxx-xxx");
//create the http request content
HttpContent content = new StringContent(json.ToString());
try
{
// Send the json to the server using POST
Task<HttpResponseMessage> getResponse = httpClient.PostAsync(uri, content);
// Wait for the response and read it to a string var
HttpResponseMessage response = await getResponse;
responseStr = await response.Content.ReadAsStringAsync();
}
catch (Exception e)
{
Console.WriteLine("Error communicating with the server: " + e.Message);
}
}
return responseStr;
}
I'm running this on Android 4.4 via a Nexus 4. I'm on 3G (not wifi).
Any hints as to what might be happening here and why i'm getting the error.
In case the url request is in local network, Check if you url ip is set in the hosts device (the hosts setting of the smartphone, tablet, whatever you are using to test)
PD.
To edit the hosts setting device in android you may use this app
https://play.google.com/store/apps/details?id=com.nilhcem.hostseditor

Categories

Resources