quilkin quilkin - 1 year ago 274
Android Question

Connection to local web service from xamarin Vs2015 android emulator

I am getting 'connection refused' or 'bad request' when trying to connect from the android emulator to my web service on localhost. I have added the port number to the firewall to allow connections, and I have tried the advice given here to modify applicationhost.config

Both the web service and the emulator are running on the same (Windows 10) PC. In the server's web.config I have the following under 'system.webserver':

<clear />
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, PUT, POST" />

AFAIK the emulator can find the web server (I'm not getting a 'not found' error), but the server refuses a connection.

using (WebClient client = new WebClient())
string json = ......;
client.Headers[HttpRequestHeader.ContentType] = "application/json";
// I have also tried "application/x-www-form-urlencoded";
string result = client.UploadString(UrlBase.urlBase + "SaveLocation", json);

If 'UrlBase' is, I get 'Bad request', which I know can result from badly formatted json.

If 'UrlBase' is a remote server, the connection works (so I know the json format is correct). Same updated dll running on both remote and local server.

If 'UrlBase' is http://localhost:60080/Service1.svc/, I get exception 'connection refused'

Answer Source

I am not using any firewall rules because my emulator is on the same machine as the service host. As Jason said you should use your host IP address. To avoid many problems use local IIS host not IIS express. Your "Bad request" is not invalid Json but Invalid host name because IIS express will not allow ANY connections but from the local machine. You can try to trick it as in the link you referenced above but why bother?

This is the result of IIS Express hosted app.

enter image description here

This is the result of local IIS hosted app

enter image description here

After getting the project here is the result:

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download