Android MySQL Connection
I am trying to connection with php-MySQL using below code
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://127.0.0.1/mytable.php");
// HttpPost httppost = new HttpPost("http://localhost/mytable.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag"开发者_C百科, "Error in http connection"+e.toString());
}
when control goes on httpclient.execute(httppost);
it throws an exception:
org.apache.http.conn.HttpHostConnectException: Connection to http://127.0.0.1 refused
I also add <uses-permission android:name="android.permission.INTERNET" />
to my AndroidManifest.xml file.
When I test my php file directly from a browser, it works fine. Any suggestions?
From the emulator, il you want to access your physical computer, you must use the following IP address :
10.0.2.2
The one you used, 127.0.0.1
, points to the machine inside which your code is executed -- i.e. the emulator itself.
As you don't have an HTTP server running on your Android emulator, your application cannot connect to it -- which explains the error message you get.
For more informations, you should read the following section of the manual : Network Address Space
127.0.0.1 is localhost, the current device. On your computer, it refers to your computer, but on a device or an emulator it refers to that device.
See this document on how to refer to the localhost of your computer when running within an emulator. Alternatively, you can change 127.0.0.1 to your computer's actual IP address.
http://developer.android.com/resources/faq/commontasks.html#localhostalias
精彩评论