I added a Java app engine servlet backend to my app, and in my "client" I have a ServletPostAsyncTask class performing an http request to my backend.
If I use an emulator, I can access my backend through the IP address 10.0.2.2:8080, but if I run on a physical device, I receive the "http://10.0.2.2:8080 connection refused" error.
Now, I can't use localhost or 127.0.0.1 or 10.0.2.2 because with localhost I would be trying to connect to my own smartphone, and 10.0.2.2 is the Special alias to my host loopback interface and is therefore suitable for use only from an emulator. But then, isn't there any alias address created to point to my development machine from a physical device?
I just can't wrap my head around it.
This is my code. Class ServletPostAsyncTask in "client" performing the HTTP request:
class ServletPostAsyncTask extends AsyncTask<Pair<Context, String>, Void, String> {
private Context context;
@Override
protected String doInBackground(Pair<Context, String>... params) {
context = params[0].first;
String name = params[0].second;
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://myIPaddress:8080/hello");
// http://10.0.2.2:8080 is localhost's IP address in Android emulator
try {
// Add name data to request
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("name", name));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(response.getEntity());
}
return "Error: " + response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase();
} catch (ClientProtocolException e) {
return e.getMessage();
} catch (IOException e) {
return e.getMessage();
}
}
@Override
protected void onPostExecute(String result) {
Toast.makeText(context, result, Toast.LENGTH_LONG).show();
}
}
As a consequence to this issue, when I run on any of the mentioned addresses I get this error: "http://myIPaddress:8080 connection refused"
<uses-permission android:name="android.permission.INTERNET" />
in my manifest fileWhy isn't there a similar alias to use from physical devices? If there isn't, then what my IP address should be?
I've solved it. I discovered that the router were I'm connected is blocking the traffic. I've tried both with another router and with my mobile service provider's network: connecting both my laptop and my device over the same network did part of the job.
I also had to change configurations (run -> change configurations) and create a new backend configuration.
This backend's configuration need to have a Server address listening to the computer's IP address instead of the default "localhost". Apparently, only this way the client and backend addresses will match. Of course the http request needs to be over the same IP address where the backend is listening.