Xamarin: connecting to a locally hosted web service

I want to create a web api application to connect xamarin with Android.
I tried a lot, but some connection errors go.

My code is below:

public async Task<JsonValue> find(int ID) { using (HttpClient client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:49836"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage result = client.GetAsync("api/Product").Result; return JsonConvert.DeserializeObject<JsonValue>(await result.Content.ReadAsStringAsync()); } } } 

I get an error as below

System.Net.WebException: Error: ConnectFailure (connection rejected) ---> System.Net.Sockets.SocketException: connection rejected

Can anyone help. Any help is appreciated.

+8
web-services xamarin xamarin.android
source share
3 answers

Please note: if your web services are hosted on IIS Express, you should be aware that you cannot connect to IIS Express from external devices, because by default IIS Express only responds to a request from the local computer. Therefore, from android emulators as external (virtual) devices, we cannot send requests to IIS Express. The solution is to use IIS instead of IIS Express.

  • Use IIS or configure IIS Express to serve external requests.
  • In Android Emulator, you cannot use "localhost" because "localhost" is a loopback and refers to the Android emulator. Instead, you need to access your web service using the IIS IP address.
  • Configure your system's firewall to allow incoming HTTP requests.
+18
source share

I solved the problem of downloading data from the server via asp.net web api, and for a start I recommend a simple way.

Try using the full address, for example.

Make sure you are connected to the data.

Make sure you have the correct path (for example, when you turn on Wi-Fi, which goes through the server on which you use WebAPI, and not the full address, but the address of the local server).

Here is a simple code that works in my case (start with a simple one and then move on)

  using (WebClient webClient = new WebClient()) { webClient.Encoding = System.Text.Encoding.UTF8; string result = webClient.DownloadString(new Uri("https://webapi.domain.cz/api/root")); } 
+2
source share

I solved this problem using IP address without using localhost

0
source share

All Articles