Xamarin: Connect to locally hosted web service

36,630

Solution 1

If you're using an Android Emulator then asking for the localhost web service won't work, because you're looking at the localhost of the emulator. How can you fix this? Well, Android Emulator has a magic address http://10.0.2.2:your_port that points to 127.0.0.1:your_port on your host machine.Take a look here. Because it points to an IP and not localhost, you need to go into your project solution, in .vs folder->config->applicationhost.config and change this <binding protocol="http" bindingInformation="*:13142:localhost" /> into <binding protocol="http" bindingInformation="*:13142:127.0.0.1" />, where 13142 is my port, yours may be different. Restart IIS Express and you're good to go.

Solution 2

Note that, If your web services is hosted by IIS Express, then you should know you can not connect to IIS Express from external devices, because inherently IIS Express only responding to request of the local machine. So from android emulators as a external (virtual) devices, we can not send requests to IIS Express. The solution is to use IIS instead of IIS Express.

  1. Use IIS or configure IIS Express to service to external requests.
  2. In Android Emulator you can not use 'localhost', because 'localhost' is loopback and refers to Android emulator. Instead you have to address your web service by using the IP of IIS.
  3. Configure Firewall of your system, to allow http requests to come in.

Solution 3

i solved this problem by using IP address not use localhost

Solution 4

I solved the problem of how to download data from the server through asp.net web api and for start i recomend the simple way.

Try to use the full address eg.

Check that you have data connection turned on.

Make sure that you have the correct path (eg. When you turn on wifi, which goes through the server on which you WebAPI, so not full address, but the address of a local server).

Here is simple code which running in my case (start from simple and then go next)

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

Solution 5

Try changing your Hosts file adding a new hostname to 127.0.0.1

127.0.0.1  mylocalmachine #this name can be any you want

Now you can request with this url

client.BaseAddress = new Uri("http://mylocalmachine:49836"); 

That happens because localhost is in the context of your emulator, so is calling localhost of the phone.

Instead of using hostname you can do what Culy Ch aims.

Share:
36,630
Admin
Author by

Admin

Updated on June 12, 2021

Comments

  • Admin
    Admin almost 3 years

    I want to create a web api application to connect xamarin with android.
    I had tried a lot, but some connection errors are coming.

    My code is given 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 'm getting the error like the below

    System.Net.WebException: Error: ConnectFailure (Connection refused) ---> System.Net.Sockets.SocketException: Connection refused

    Can any one help. Any help is appreciated.

  • Admin
    Admin almost 9 years
    right now i have another problem:-- result = {StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { Server: Microsoft-HTTPAPI/2.0 Date: Wed, 01 Jul 2015 05:57:12 GMT Connection: close Content-Type: text/html; charset=us-ascii Content-Lengt...
  • Majkl
    Majkl almost 9 years
    Check that the input data request are correct. E.g. if you have json data than you can not : Content-Type: text / html. I usually first try to query the server in a Fiddler2 and When i have right format and answer is OK, than the same query / url try in the target application...
  • Majkl
    Majkl almost 9 years
    btw, If my answer to your question is correct / instrumental do not forget mark it as answered.
  • Ali Kahaei
    Ali Kahaei about 7 years
    @Ehsad Mirsaeedi I wish you had given a more complete answer of how to exactly do each of these things so that everybody could use it.
  • Prabesh
    Prabesh about 6 years
    Saved me after hours of searching.
  • vivek ramasamy
    vivek ramasamy over 3 years
    Worked like a charm !! thanks . after very long searching fruitful answer