0

i'm trying to connect to xampp localhost trough android emulator using android studio. but im always getting a connection refused error.

i've read around and tried most solution such as changing localhost to 10.0.2.2 or 127.0.0.1 or 192.168.0.1 and even tried to remove the http:// or add port :8080 behind it. but still no luck.

i can run the localhost/test.php in the browser with no problem. but 10.0.2.2/test.php doesnt work.

and ofcourse i added internet permission to the manifest.xml too.

i've even tried 2 version of code but it still fails me. can anyone please help me to understand this?

here's the error shown.

04-10 02:55:15.933    2162-2178/com.example.kitd16.myapplication W/System.err﹕ java.net.ConnectException: failed to connect to /10.0.0.2 (port 80) after 60000ms: isConnected failed: ECONNREFUSED (Connection refused)

here's the code that i've tried.

URL url = new URL("http://127.0.0.1/cloudtest/test.php");

                            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

                            conn.setReadTimeout(30000 /* milliseconds */);
                            conn.setConnectTimeout(60000 /* milliseconds */);
                            conn.setDoOutput(true);
                            conn.setRequestMethod("POST");
                            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                            conn.setRequestProperty("charset", "utf-8");
                            conn.setRequestProperty("Content-Length", "" + et.getText().toString());
                            conn.setUseCaches(false);
                            conn.setInstanceFollowRedirects(false);
                            conn.setDoInput(true);

                            //Send request
                            DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
                            wr.writeBytes(et.getText().toString());
                            wr.flush();
                            wr.close();
                            // Starts the query
                            conn.connect();
                            is = (BufferedInputStream) conn.getInputStream();

                        } catch (Exception ex) {
                            System.out.println("first error");
                            ex.printStackTrace();
                            System.exit(0);
                        } finally {
                            if (is != null) {
                                try {
                                    is.close();
                                } catch (Exception ex) {

                                }
                            }
                        }

2nd version

b.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            final ProgressDialog p = new ProgressDialog(v.getContext()).show(v.getContext(),"Waiting for Server", "Accessing Server");
            Thread thread = new Thread()
            {
                @Override
                public void run() {
                     try{

                         httpclient=new DefaultHttpClient();
                         httppost= new HttpPost("http://10.0.0.2/my_folder_inside_htdocs/connection.php"); // make sure the url is correct.
                         //add your data
                         nameValuePairs = new ArrayList<NameValuePair>(1);
                         // Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
                         nameValuePairs.add(new BasicNameValuePair("Edittext_value",et.getText().toString().trim()));  // $Edittext_value = $_POST['Edittext_value'];
                         httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                         //Execute HTTP Post Request
                         response=httpclient.execute(httppost);

                         ResponseHandler<String> responseHandler = new BasicResponseHandler();
                         final String response = httpclient.execute(httppost, responseHandler);
                         System.out.println("Response : " + response);
                         runOnUiThread(new Runnable() {
                                public void run() {
                                    p.dismiss();
                                     tv.setText("Response from PHP : " + response);
                                }
                            });

                     }catch(Exception e){

                         runOnUiThread(new Runnable() {
                            public void run() {
                                p.dismiss();
                            }
                        });
                         System.out.println("Exception : " + e.getMessage());
                     }
                }
            };

            thread.start();
Yoh Hendry
  • 417
  • 6
  • 15
  • 1
    127.0.0.1 won't work for emulator try 10.0.0.2, kindly put your log in your question, can you access same php file using your browser – Pankaj Nimgade Apr 10 '15 at 06:52
  • i think you added Internet permission in manifest file – Praveen B. Bhati Apr 10 '15 at 06:54
  • tried the 10.0.0.2 and yes i've added it. still doesnt work. i just keep getting that same error. – Yoh Hendry Apr 10 '15 at 06:58
  • Did you try this : http://stackoverflow.com/questions/20015883/connecting-localhost-via-android-connection-to-10-0-2-2-refused/22313837#22313837 use your system ip rather than 10.0.0.2 or 127.0.0.1 – Raghavendra Apr 10 '15 at 07:07
  • try putting any index.html in main xampp directory and test 10.0.2.2 in emulator browser, if this works it will also work for other files. – Harin Apr 10 '15 at 10:54

1 Answers1

0

For me using my own PC IP address worked with Android Studio emulator. After button click-

HttpPost httpPost=new HttpPost("http://192.168.104.222/index.php");

I used Strict Mode Policy in the onCreate Method:

protected void onCreate(Bundle savedInstanceState) { 
//Strict Mode Policy
  StrictMode.ThreadPolicy policy =new StrictMode.ThreadPolicy.Builder().permitAll().build();
  StrictMode.setThreadPolicy(policy);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_activity_login);
    eName=(EditText)findViewById(R.id.etName);
}
 public void Login(View v){

    InputStream is=null;
    String name=eName.getText().toString();

    List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>(1);
    nameValuePairs.add(new BasicNameValuePair("name",name));

    try{
        //Setting up the default http client
        HttpClient httpClient =new DefaultHttpClient();
        //Setting up the http post method & passing the url in case
        //of online database and the IP address in case of localhost database
        //And the php file which serves as the link between the android app
        //and the database.
        //Second parameter is the php file to link with database

        HttpPost httpPost=new HttpPost("http://192.168.104.222/tutorial.php");

        //Passing the nameValue pairs inside the httpPOST
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        //Getting the response
        HttpResponse response =httpClient.execute(httpPost);

        HttpEntity entity =response.getEntity();
        is=entity.getContent();

        //confirmation
        String msg ="Data Entered Successfully";


    }catch(ClientProtocolException e){
        Log.e("ClientProtocol","Log_TAG");
        e.printStackTrace();

    }catch(IOException e){
      // Log.e("IO Error","Log_TAG");
        e.printStackTrace();

    }


}
Shudy
  • 7,806
  • 19
  • 63
  • 98