30

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.

Marvin Dickhaus
  • 686
  • 12
  • 27
jayeshmon kj
  • 301
  • 1
  • 3
  • 3
  • Looks like this has nothing to do with your code, the address you are trying to reach; `http://localhost:49836` is unreachable. Are you sure the port is correct? Is a server listening? Is the firewall letting traffic through? What do you see when you type that address in your browser? – Gerald Versluis Jun 30 '15 at 07:10
  • possible duplicate of [Connect to localhost from android device](http://stackoverflow.com/questions/10309049/connect-to-localhost-from-android-device) – user1 Jun 30 '15 at 08:08
  • 2
    "localhost" refers to the DEVICE you are running on. If you want to connect to an another system, you need to use it's unique IP or name, not localhost. – Jason Jun 30 '15 at 12:32
  • 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... – jayeshmon kj Jul 01 '15 at 06:19
  • i need help statuscode :- 400,any other settings are required for connecting web api – jayeshmon kj Jul 02 '15 at 12:11

6 Answers6

47

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.

Culy Ch
  • 451
  • 5
  • 8
31

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.
Ehsan Mirsaeedi
  • 5,042
  • 32
  • 36
  • 10
    @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. – Ali Kahaei Mar 07 '17 at 08:00
3

i solved this problem by using IP address not use localhost

hosam hemaily
  • 285
  • 3
  • 13
2

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"));              
            }
Majkl
  • 767
  • 1
  • 8
  • 24
  • 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... – jayeshmon kj Jul 01 '15 at 06:18
  • 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 Jul 01 '15 at 06:27
  • btw, If my answer to your question is correct / instrumental do not forget mark it as answered. – Majkl Jul 01 '15 at 06:29
1

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.

Gabriel Castillo Prada
  • 2,619
  • 3
  • 17
  • 25
0

If your Web Service is hosted by IIS, then you will need to do some extra setup in order to accept requests coming from external devices or servers. (iOS simulator, separate project on another developers machine, etc.)

In order to do this, follow the suggestions in this Stack Overflow answer: How to enable external request in IIS Express?

AndrewGentry
  • 152
  • 12