简体   繁体   中英

Why can't my app connect to localhost with easyphp devserver?

I'm making an android app that retrieves informations from a web page. In short, there's the code:

    protected Void doInBackground(String... params) {
        HttpURLConnection conn = null;
        try {
            URL url;
            url = new URL(getHomeUrl() + "myPage.php");
            conn = (HttpURLConnection) url.openConnection();
            if( conn.getResponseCode() == HttpURLConnection.HTTP_OK ){
                doThings(conn);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(conn != null) {
                conn.disconnect();
            }
        }        
        return null;
   }

If the url is http://www.mywebsite.com/myPage.php , the connection is OK. But if the url is http://localhost/myPage.php or http://127.0.0.1:80/myPage.php with easyphp devserver on, I catch an IOException and get this:

  • on android emulator => java.net.ConnectException: Connection refused
  • on physical device (as deployment target) => java.net.ConnectException: failed to connect to /127.0.0.1 (port 80): connect failed: ECONNREFUSED (Connection refused)

For information, when I copy paste http://127.0.0.1:80/myPage.php in my browser, the access is granted.

I read that android emulator could "use" localhost, and it is suggested to take 10.0.2.2 instead, but it didn't work either. I guess this is a matter of apache conf, but I have this, that seems correct to me:

<Directory "D:/Utilitaires/EasyPHP-Devserver-17/eds-www">
        Options FollowSymLinks Indexes ExecCGI
        AllowOverride All
        Order deny,allow
        Allow from 127.0.0.1
        Deny from all
        Require all granted
    </Directory>

Any idea?

Your server is running on your computer, so 127.0.0.1 is working only on that machine. If you would like to access it from your phone you should write your computer's local address (ie: 192.168.10.100 ). It will be working fine if your network is configured properly.

I recommend to you that upload your website to a public host and you can easily access it from your mobile app.

Got it ! It failed with http://10.0.2.2 , but it's ok with http://10.0.2.2:80 !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM