I am adding a "App Engine Java Servlet Module" Template as a backend to my app, so I am performing an 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://10.0.2.2: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();
}
}
The problem is that when I execute I get this error: http://10.0.2.2:8080 connection refused
I already tried for several solutions:
- I already have <uses-permission android:name="android.permission.INTERNET" /> in my manifest file
- I know that 10.0.2.2 is the equivalent of 127.0.0.1 when I use the emulator, in fact this code works within my emulator but doesn't within my physical device
- I've tried with http://localhost:8080 but still, same error
Reading around I learned that localhost corresponds to the hostname of my device, not of the machine where the Servlet is, but really then, I have no clue on what the address could be!
I've also tried with my machine's IP address, but in this case I don't get any Toast message, wheter error or not, just nothing pops out... could this be a hint?
I would really appreciate your backup.
I already tried several solutions:
<uses-permission android:name="android.permission.INTERNET" /> in my manifest fileReading around I learned that localhost corresponds to the hostname of my device, not of the machine where the Servlet is, but then I have no clue on what the address could be.
I've also tried with my machine's IP address, but in this case I don't get any Toast message, wheter error or not, just nothing pops out... could this be a hint?
I would really appreciate your backup here.
Check to make sure you are making a post request. That's what the servlet is set up to listen for.
It's not so easy to make one from the browser.