安卓连接本地主机

22

我正在尝试将我的安卓应用连接到WAMP服务器的本地主机URL,但无法成功。我的目标是获取JSON数据并解析这些数据。为了测试,我使用的是设备而非模拟器,并且在AndroidManifest.xml中使用了权限:

<uses-permission android:name="android.permission.INTERNET" />

我的网址看起来像这样:

String url = "http://10.0.2.2:8080/tests/PhpProject1/connectionBDD.php";

我尝试过:

http://localhost/
http://10.0.2.2:8080/
http://10.0.2.2/

但是到目前为止它从未起作用:

    java.net.ConnectException: failed to connect to localhost/127.0.0.1 (port 80): connect failed: ECONNREFUSED (Connection refused)

    failed to connect to /10.0.2.2 (port 8080): connect failed: ETIMEDOUT (Connection timed out)

    java.net.ConnectException: failed to connect to /10.0.2.2 (port 80): connect failed: ETIMEDOUT (Connection timed out)

然后我尝试了一个在互联网上找到的JSON URL测试:http://headers.jsontest.com/

它运行得非常好,我可以在这个地址获得JSON数据。所以我想我的代码没有问题,问题出在我的本地主机URL上,我不知道应该是什么样的确切形式。 我阅读了许多相关帖子,但没有找到解决办法。

这是我的代码:

主要活动:

public class MainActivity extends Activity {
    private String url = "http://10.0.2.2:8080/tests/PhpProject1/connectionBDD.php";

    private ListView lv = null;
    private Button bGetData;

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final JsonDownloaderTask task = new JsonDownloaderTask(this);
        lv = (ListView) findViewById(R.id.list);

        bGetData = (Button)findViewById(R.id.getdata);
        bGetData.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {               
                task.execute(url);                      
            }
        });
    }

    public void jsonTaskComplete(JSONArray data){
        //todo
    }   
}

异步任务:

public class JsonDownloaderTask extends AsyncTask<String, String, JSONArray> {

    MainActivity ma;

    public JsonDownloaderTask(MainActivity main){
        ma = main;
    }

    @Override
    protected JSONArray doInBackground(String... url) {
        JSONParser jParser = new JSONParser();
        // Getting JSON from URL
        JSONArray jsonArray = null;
        try {
            jsonArray = jParser.getJSONFromUrl(url[0]);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonArray;        
    }

    protected void onPostExecute(JSONArray data){

        ma.jsonTaskComplete(data);
    }
}

JSON解析器:

public class JSONParser {
    String data = "";
    JSONArray jsonArray = null;        
    InputStream is = null;

    public JSONParser(){}

    // Method to download json data from url
    public JSONArray getJSONFromUrl(String strUrl) throws IOException{
        try{
            URL url = new URL(strUrl);

            // Creating an http connection to communicate with url
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            // Connecting to url
            urlConnection.connect();

            // Reading data from url
            is = urlConnection.getInputStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(is));

            StringBuffer sb  = new StringBuffer();

            String line = "";
            while( ( line = br.readLine())  != null){
                sb.append(line);
            }
            is.close();
            data = sb.toString();

            //br.close();

            jsonArray = new JSONArray(data);

        }catch(Exception e){
            Log.d("Exception while downloading url", e.toString());
        }finally{
            is.close();
        }

        return jsonArray;
    }
}
9个回答

14

IP地址10.0.2.2用于从模拟器中获取数据。 Localhost将始终指向运行应用程序的模拟器/Android设备。 要让您的设备从电脑上获取数据,它应该连接到同一个网络(通过WiFi连接到您的路由器),并且您应该使用您电脑的本地IP地址(通常是192.168.1.x号码)。


1
我已经尝试使用我的笔记本电脑的IP地址,但仍然无法连接。 - Dev
这仅适用于模拟器,而问题明确表示正在使用设备。 - Chris Stratton
1
不,如果PC上运行的服务器在本地网络中可访问,则使用PC的192.168.1.x IP地址连接可以与物理设备配合使用。在我的回答中,我首先解释了为什么问题中的代码无法正常工作。 - user3316041

6
如果您尝试连接到“localhost”,它将解析为Android设备,而不是您自己的本地主机(除非您在模拟器中运行)。我建议在操作栏中添加一个溢出菜单,其中包含名为“设置”的条目,提供一个设置活动以指定应用程序设置,并在“设置”中有一个“开发人员选项”条目,让您指定要使用的自定义服务器地址。在开发过程中,您可以使用此选项为您的应用程序输入自定义服务器地址。(您需要一个实际可通过互联网访问的真实服务器地址,而不是使用localhost)

4

首先,您需要在Eclipse设置中绑定运行服务器的计算机的IP地址。

可以按照以下步骤操作:

Eclipse Run Configuration

右键单击Eclipse中的PHP项目,然后选择Run Configuration,进入Web Application选项卡,找到Argument选项卡。现在在这里输入您的机器上运行服务器的端口和LAN IP地址。

类似于这样:--port=8888 --address=192.168.1.6,然后将URL更新为http://192.168.1.6:8080/tests/PhpProject1/connectionBDD.php

在我的情况下,这是我的LAN IP地址 192.168.1.6,请使用网络命令(如ipconfigifconfig)查找并使用该IP地址。


谢谢你的回答,我用NetBeans解决了这个问题,现在urlConnection.connet();可以正常工作了,但是我又遇到了另一个异常:java.net.SocketException: recvfrom failed: ECONNRESET (Connection reset by peer),也许你知道这个问题。 - Alex DG
好的,针对这个新问题,您可以在这里阅读https://dev59.com/12gu5IYBdhLWcg3wnYLo,现在您可以接受答案。 - Ajay S
2
我该如何在Android Studio上实现这个? - MiraTech
1
在Android Studio中我该怎么做? @AbdelazizMirad,你找到解决方案了吗? - doubleOrt
@Taurus -- 请在这个问题中查看我的答案。它非常简单明了,您一定能够理解。 - Saumik Bhattacharya
显示剩余4条评论

3
如果您使用手机而非模拟器,并在本地主机上运行服务,则在URL中,不要使用'10.0.2.2',而应使用您电脑的IP地址。

1
我通过以下方式解决了问题: 1. 在清单文件中添加另一个Android权限:"android.permission.ACCESS_NETWORK_STATE" 2. 因为我使用的是xampp,所以我在网络中共享了桌面上xampp文件夹。 3. xampp正在运行的桌面的IP地址是192.168.x.x,因此Web服务的URL不再是"http://localhost/myapi...",而是"http://192.168.x.x/myapi..."。
我在模拟器和设备上测试了该应用程序。两种情况都可以正常工作。

0

我试过"10.0.2.2:80/mysitename/page.php"

奇迹发生了,现在可以使用了。

我正在使用Mac和XAMPP服务器。

你可以更改端口号为80并尝试连接。 对我来说,8080端口无法工作!

干杯。


这仅适用于模拟器,而问题明确指定了物理设备。 - Chris Stratton

0

我知道的一种简单方法是保持移动数据开启并共享WiFi。将您的笔记本电脑或计算机连接到此WiFi。现在查看您的笔记本电脑或台式机的IP地址。从您的手机上拨打服务电话。由于您的手机和计算机现在处于同一网络中。


0
只需在Visual Studio中安装“Keyoti的conveyor”扩展程序,它将自动根据您的IP地址生成一个URL。这是链接:

conveyor

到目前为止一切都很好....!


0

我猜你想要从安卓模拟器或真实设备上访问你PC上的网络服务。

对于安卓模拟器,你不应该只使用“localhost”,因为“localhost”指代的是模拟器本身,而非主机PC。

你需要修改模拟器或真实设备的/etc/hosts文件。添加一行类似于“192.168.0.100 service.local”的内容。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接